You are on page 1of 55

SQL - Databases

What's a Database? A SQL database is nothing more than an


empty shell, like a vacant warehouse. It offers no real
functionality whatsoever, but does provide a virtual space to
store data. Data is stored inside of database objects called
tables, and tables are the containers that actually hold specific
types of data, such as numbers, files, strings, and dates.

A single database can house hundreds of tables containing more


than 1,000 table columns each and they may be jam packed
with relational data ready to be retrieved by SQL. Perhaps the
greatest feature SQL offers is that it doesn't take much effort to
rearrange your warehouse to meet your ever-growing business
needs.

SQL - Creating a Database


Creating a database inside of SQL Express has its advantages.
After launching Microsoft's SQL Server Management Studio
Express application, simply right-clicking on the Databases
folder of the Object Explorer gives you the option to create a
New Database. After selecting the New Database... option,
name your database "MyDatabase" and press "OK".

Now is the time to press the New Query button located toward
the top of the screen, just above the Object Explorer pane.

Pressing this button offers an empty tab. All SQL query


statements (code) that we will be exploring will be entered here
and executed against the SQL Express database.

If you haven't yet created a new database, you may also create a
database by typing the following SQL query statement into
your new empty query tab, and then pressing the Execute
button or striking the (F5) key.

SQL Create Database Query:


CREATE DATABASE MyDatabase;

After executing this query, SQL will notify you that your query
has run successfully and that the database was created
SQL - Tables
Data is stored inside SQL tables which are contained within SQL
databases. A single database can house hundreds of tables, each
playing its own unique role in the database schema. While
database architecture and schema are concepts far above the scope
of this tutorial, we plan on diving in just past the surface to give
you a glimpse of database architecture that begins with a thorough
understanding of SQL Tables.

Advertise on Tizag.com

SQL tables are comprised of table rows and columns. Table


columns are responsible for storing many different types of data,
like numbers, texts, dates, and even files. There are many different
types of table columns and these data types vary, depending on
how the SQL table has been created by the SQL developer. A table
row is a horizontal record of values that fit into each different
table column.

SQL - Create a SQL Table


Let's now CREATE a SQL table to help us expand our knowledge
of SQL and SQL commands. This new table will serve as a
practice table and we will begin to populate this table with some
data which we can then manipulate as more SQL Query
commands are introduced. The next couple of examples will
definitely be overwhelming to novice SQL programmers, but we
will take a moment to explain what's going on.

SQL Create Table Query:


USE mydatabase;

CREATE TABLE orders


(id INT IDENTITY(1,1) PRIMARY KEY,
customer VARCHAR(50),
day_of_order DATETIME,
product VARCHAR(50),
quantity INT);

The first line of the example, "USE mydatabase;", is pretty


straightforward. This line defines the query scope and directs
SQL to run the command against the MyDatabase object we
created earlier in the SQL Databases lesson. The blank line break
after the first command is not required, but it makes our query
easier to follow. The line starting with the CREATE clause is
SQL - Queries
SQL coins the term query as the name for its commands. Basically, all SQL code is written in the form
query statement and then executed against a database. All SQL queries perform some type of data opera
such as selecting data, inserting/updating data, or creating data objects such as SQL databases and SQL
tables. Each query statement begins with a clause such as SELECT,UPDATE, CREATE or DELETE.

Advertise on Tizag.com

SELECT queries are the most commonly used SQL commands, so let's take a look at a SELECT query
will return records from the orders table that we created previously in the SQL Tables lesson.

SQL Query Code:


USE mydatabase;

SELECT * FROM orders;

SQL Query Results:


id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4
We'll explain the mechanics of this code in the next lesson. For now, just know that SELECT queries
essentially tell SQL to go and "fetch" table data for your viewing pleasure.

Here's a look at a few different query types including a INSERT and SELECT query we will be coveri
the next lesson, SQL Select.

SQL Query Examples:


-- Inserts data into a SQL Database/Table
INSERT INTO orders (customer,day_of_order,product, quantity)
VALUES('Tizag','8/1/08','Pen',4);

-- Selects data from a SQL Database/Table


SELECT * FROM orders;

-- Updates data in a Database/Table


UPDATE orders SET quantity = '6'
WHERE id = '1'
SQL - Select
SQL SELECT may be the most commonly used command by SQL programmers. It is used to extract d
from databases and to present data in a user-friendly table called the result set.

Advertise on Tizag.com

SQL Select Query Template:


SELECT table_column1, table_column2, table_column3
FROM my_table;

Select queries require two essential parts. The first part is the "WHAT", which determines what we wa
SQL to go and fetch. The second part of any SELECT command is the "FROM WHERE". It identifie
where to fetch the data from, which may be from a SQL table, a SQL view, or some other SQL data ob

Now we would like SQL to go and fetch some data for us from the orders table that was created in the
previous lesson. How do we translate this request into SQL code so that the database application does a
work for us? Simple! We just need to tell SQL what we want to select and from where to select the da
following the schema outlined below.

SQL Select Query Code:


USE mydatabase;

SELECT id, customer, day_of_order, product, quantity


FROM orders;

SQL Orders Table Results:


id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4
Below, we will manipulate the result output by rearranging the list of table column names inside of the
SELECT statement.

SQL Select Query: Rearranged:


USE mydatabase;
SQL - Where
The WHERE clause sets a conditional statement, and it can be used with any type of SQL query. As t
select query executes, SQL processes one row at a time. Each time the conditional statement is met
(returns true), a row is returned as a result. SQL WHERE is essentially, a filtering mechanism for SQL
queries and is a tremendous asset to any aspiring SQL developer.

Advertise on Tizag.com

SQL Where Query:


USE mydatabase;

SELECT *
FROM orders
WHERE customer = 'Tizag'

As we take a look at the results, notice how only the rows that meet the criteria (where the customer co
value is Tizag) are returned. In this example, we are using the WHERE clause to filter out rows and on
selecting data that meets the conditional statement.

SQL Results:
id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4
2
Tizag
2008-08-01 00:00:00.000
Stapler
1
5
Tizag
2008-07-25 00:00:00.000
19" LCD Screen
3
6
Tizag
2008-07-25 00:00:00.000
HP Printer
SQL - As
SQL AS temporarily assigns a table column a new name. This grants the SQL developer the ability to m
adjustments to the presentation of query results and allow the developer to label results more accurately
without permanently renaming table columns.

Advertise on Tizag.com

SQL Select As Code:


USE mydatabase;

SELECT day_of_order AS "Date",


customer As "Client",
product,
quantity
FROM orders;

SQL Orders Table Results:


Date
Client
product
quantity
2008-08-01 00:00:00.000
Tizag
Pen
4
SQL AS allows us to use any name at the presentation level and helps the developer better describe a
column in the result set.

SQL Select Arithmetic Query:


USE mydatabase;

SELECT (5 + 12) AS "5 plus 12 is"

SQL Arithmetic Results:


5 plus 12 is
17
SQL - Operators
SQL operators are found in just about every SQL query. Operators are the mathematical and equality
symbols used to compare, evaluate, or calculate values. Equality operators include the (<), (>), and (=)
symbols, which are used to compare one value against another. Each of these characters have special
meaning, and when SQL comes across them, they help tell SQL how to evaluate an expression or
conditional statement. Most operators will appear inside of conditional statements in the WHERE claus
SQL Commands.

Advertise on Tizag.com

Operators come in three flavors: mathematical, logical, and equality. Mathematical operators add, subtr
multiply, and divide numbers. Logical operators include AND and OR. Take note of the following table
future reference.

SQL operators are generally found inside of queries-- more specifically, in the conditional statements o
WHERE clause.

SQL Equality Operator Query:


USE mydatabase;

SELECT customer,day_of_order
FROM orders
WHERE day_of_order > '7/31/08'

Sql Equality Operator:


customer
day_of_order
Tizag
2008-08-01 00:00:00.000
Tizag
2008-08-01 00:00:00.000
In this case, we've used the equality operator greater than (>) to return orders from the orders table wit
date greater than '7/31/08'.

SQL - Equality Operator Table


Equality involves comparing two values. To do so requires the use of the (<), (>), or (=) special charact
Does X = Y? Is Y < X? These are both questions that can be answered using a SQL Equality Operator
expression.

SQL Equality Operators:


Operator
SQL - Create
SQL CREATE is the command used to create data objects, including everything from new databases a
tables to views and stored procedures. In this lesson, we will be taking a closer look at how table crea
is executed in the SQL world and offer some examples of the different types of data a SQL table can ho
such as dates, number values, and texts.

Advertise on Tizag.com

To accomplish this, it is best to first take a look at the entire CREATE TABLE query and then review e
line individually.

SQL Create Table Code:


USE mydatabase;

CREATE TABLE inventory


(
id INT IDENTITY(1,1) PRIMARY KEY,
product VARCHAR(50) UNIQUE,
quantity INT,
price DECIMAL(18,2)
);

Line 1 identifies the scope of the query specifying a target database for query execution (USE mydatab
and we've seen it before so let's skip ahead to the next line, line 2 (CREATE TABLE inventory). This li
informs SQL of the plan to create a new table using the CREATE clause and specifies the name of the
table (inventory). In this case, we plan on creating an inventory table to maintain a current inventory of
items for an imaginary e-commerce web site.

SQL Create Line 3:


id INT IDENTITY(1,1) PRIMARY KEY,

Line 3 should appear more foreign as there is a lot of information embedded in this line, but it is not as
as it seems. This is the first line that declares how to set up the first table column inside the new invento
table.

• id = The name of this new table column.


• INT = The data type. INT is short for integer.

The first word, id, is the name of this new column and the second word declares the data type, INT
(integers). SQL will now expect this table column to house only integer data type values.

• IDENTITY (1,1) = The id column will be an identity column.

The next phrase, IDENTITY (1, 1) is a very special attribute and when a table column is marked as an
identity column, the column essentially turns into an automated counter. As new rows are inserted into
SQL - Insert
To use the INSERT command, we must first have an understanding of where we would like to insert da
and what types of data we want to insert. Do we plan on inserting numbers? Strings? Files? Let's return
the orders table we created in an earlier lesson.

Advertise on Tizag.com

SQL tables store data in rows, one row after another. The INSERT command is the command used to in
new data (a new row) into a table by specifying a list of values to be inserted into each table column. T
arrangement of values is important, and how they are arranged in the code corresponds to how the data
values will be arranged in the the SQL table.

• id - (identity, integer)
• customer - (customer name, character string)
• day_of_order - (date value)
• product - (name of product, character string)
• quantity - (quantity, integer)

Looking at the column names alone will give you an idea of what type of data each column is expected
hold. The quantity column, for example, is expecting a number or integer of some sort and the day_of_
column is expecting a date value to be inserted.

SQL Insert Query:


USE mydatabase;

INSERT INTO orders (customer,day_of_order,product, quantity)


VALUES('Tizag','8/1/08','Stapler',1);

SQL Insert Results:


(1 row(s) affected)
You may notice that the id column has been left out of the query statement. The reason behind this is th
when we created the orders table, we gave the id column a unique attribute called identity. SQL handle
identity columns automatically for us and therefore, we do not need to manually insert data into this co

The first value Tizag corresponds with the customer table column. This ensures SQL will insert this val
into the corresponding table column.

Now when we run the SELECT (*) query, SQL should return two rows with our statement instead of on
single row.

Verification Query:
USE mydatabase;
SQL - And
SQL AND links together two or more conditional statements for increased filtering when running SQL
commands. AND helps the developer query for very specific records while answering questions like, "I
to view all orders made by a certain customer AND made on a special date." There is no limit to the nu
of AND/OR conditions that can be applied to a query utilizing the WHERE clause. This makes it possi
for the developer to be as precise as needed when querying for results.

Advertise on Tizag.com

SQL And Code:


USE mydatabase;

SELECT *
FROM orders
WHERE customer = 'Tizag'
AND day_of_order = '08/01/08'
AND product = 'Pen';

SQL Results:
id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4
This example illustrates how SQL AND combines multiple conditional statements (3 total now) into a s
condition with multiple circumstances (filters). Each filter removes rows from the result set that doesn't
the condition.

SQL - Or
SQL OR also applies logic to help filter results. The difference is that instead of linking together condit
statements, an OR condition just asks SQL to look for 2 separate conditions within the same query and
return any records/rows matching either of the conditions.

SQL Or Code:
USE mydatabase;
SQL - Between
BETWEEN is a conditional statement found in the WHERE clause. It is used to query for table rows th
meet a condition falling between a specified range of numeric values. It would be used to answer quest
like, "How many orders did we receive BETWEEN July 20th and August 5th?"

SQL Select Between:


USE mydatabase;

SELECT *
FROM orders
WHERE day_of_order BETWEEN '7/20/08' AND '8/05/08';

SQL Results:
id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4
2
Tizag
2008-08-01 00:00:00.000
Stapler
1
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
BETWEEN essentially combines two conditional statements into one and simplifies the querying proce
for you. To understand exactly what we mean, we could create another query without using the BETWE
condition and still come up with the same results, (using AND instead).

SQL Select Between:


SQL - Order By
ORDER BY is the SQL command used to sort rows as they are returned from a SELECT query. SQL o
by command may be added to the end of any select query and it requires at least one table column to be
specified in order for SQL to sort the results.

Advertise on Tizag.com

SQL Order by query:


USE mydatabase;

SELECT *
FROM orders
WHERE customer = 'Tizag'
ORDER BY day_of_order;

Executing this query should offer a list of orders made by Tizag and you may noticed that the result set
now been sorted (low to high) according to the date value. In other words, the oldest order to the newes
order.

SQL Results:
id
customer
day_of_order
product
quantity
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
1
Tizag
2008-08-01 00:00:00.000
Pen
4
2
Tizag
2008-08-01 00:00:00.000
Stapler
1
SQL - Update
SQL UPDATE is the command used to update existing table rows with new data values. UPDATE is a
powerful command in the SQL world. It has the ability to update every single row in a database with th
execution of only a single query. Due to UPDATE's supreme authority, it is in your best interest to alw
include a WHERE clause when working with UPDATE query statements. That way, you will not
accidentally update more rows than you intend to.

Advertise on Tizag.com

Execute the following UPDATE command to update the customer orders table. Since we've provided a
WHERE condition with this update command, this update will only modify rows that match the condit
and in this case it happens to be order number 1 made by Tizag. This update should increase the quantit
from 4 Pens to 6 Pens for Tizag's first order.

SQL Update Query:


USE mydatabase;

UPDATE orders
SET quantity = '6'
WHERE id = '1'

SQL Results:
(1 row(s) affected)
Let's verify our results by selecting this row from the orders table.

SQL Verification Query:


USE mydatabase;

SELECT *
FROM orders
WHERE id = '1'

SQL Results:
id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
SQL - Alter
SQL ALTER is the command used to add, edit, and modify data objects like tables, databases, and view
ALTER is the command responsible for making table column adjustments or renaming table columns.
table columns can also be added and dropped from existing SQL tables.

Advertise on Tizag.com

SQL Add:
USE mydatabase;

ALTER TABLE orders


ADD discount VARCHAR(10);

SQL Results:
id
customer
day_of_order
product
quantity
discount
1
Tizag
2008-08-01 00:00:00.000
Pen
8
NULL
2
Tizag
2008-08-01 00:00:00.000
Stapler
3
NULL
3
A+Maintenance
2008-08-16 00:00:00.000
Hanging Files
14
NULL
4
Gerald Garner
2008-08-15 00:00:00.000
19" LCD Screen
5
NULL
SQL - Distinct
SQL SELECT DISTINCT is a very useful way to eliminate retrieving duplicate data reserved for very
specific situations. To understand when to use the DISTINCT command, let's look at a real world exam
where this tool will certainly come in handy.

Advertise on Tizag.com

If you've been following along in the tutorial, we have created an orders table with some data inside tha
represents different orders made by some of our very loyal customers over a given time period. Let's pr
that we have just heard word from our preferred shipping agent that orders made in August require no
shipping charges, and we now have to notify our customers. We do not want to send mailers to all of ou
customers, just the ones that have placed orders in August. Also, we want to avoid retrieving duplicate
customers as our customers may have placed more than one order during the month of August.

We can write a very simple SQL query to extract this information from the orders table:

SQL Select Distinct:


USE mydatabase;

SELECT DISTINCT customer


FROM orders
WHERE day_of_order BETWEEN '7/31/08' AND '9/1/08';

SQL Results:
customer
A+Maintenance
Gerald Garner
Tizag
Running this query yields a list of all the customer's affected by our unexpected news from the shipping
agency. With this list, we can now go about contacting each of these customers and informing them of t
good news without worrying about contacting the same customer multiple times.
SQL - Subqueries
Subqueries are query statements tucked inside of query statements. Like the order of operations from y
high school Algebra class, order of operations also come into play when you start to embed SQL comm
inside of other SQL commands (subqueries). Let's take a look at a real world example involving the ord
table and figure out how to select only the most recent order(s) in our orders table.

Advertise on Tizag.com

To accomplish this, we are first going to introduce a built-in SQL function, MAX(). This function wrap
around a table column and quickly returns the current highest (max) value for the specified column. We
going to use this function to return the current "highest", aka most recent date value in the orders table.

SQL Subquery Preview:


USE mydatabase;

SELECT MAX(day_of_order)
FROM orders

SQL Results:
day_of_order
2008-08-16 00:00:00.000
Now we can throw this query into the WHERE clause of another SELECT query and obtain the results
our little dilemma.

SQL Select Subquery Code:


USE mydatabase;

SELECT *
FROM orders
WHERE day_of_order = (SELECT MAX(day_of_order) FROM orders)

:
id
customer
day_of_order
product
quantity
3
A+Maintenance
2008-08-16 00:00:00.000
Hanging Files
SQL - Join
SQL JOIN joins together two tables on a matching table column, ultimately forming one single tempor
table. The key word here is temporary. The tables themselves remain intact, and running a JOIN query
not in any way change the data or table structure. JOIN is another way to select specific data from two
more relational tables.

Advertise on Tizag.com

In order to perform a JOIN query, we need a few pieces of information: the name of the table and table
column we want to join on and a condition to meet for the JOIN to happen. This should sound a little
confusing as there is much going on in a JOIN query, so let's take a look at an example:

SQL Join Query Code:


USE mydatabase;

SELECT *
FROM orders
JOIN inventory
ON orders.product = inventory.product;

SQL Join Results:


id
customer
day_of_order
product
quantity
id
product
quantity
price
1
Tizag
2008-08-01 00:00:00.000
Hanging Files
11
5
Hanging Files
33
14.99
2
Tizag
2008-08-01 00:00:00.000
Stapler
3
4
SQL - In
SQL IN is an operator used to pull data matching a list of values. A scenario where this proves useful w
be if we wanted to retrieve customer data for two or more customers. We can use the IN operator to spe
a list of customer names, and SQL will retrieve rows reflecting every customer in the list.

Advertise on Tizag.com

Inside the query statement itself, the word "IN" replaces the (=) operator after the WHERE declarative
slightly alters the meaning as well. Instead of listing a single value, you may list multiple values and SQ
will retrieve the results for each value listed.

SQL In:
USE mydatabase;

SELECT *
FROM orders
WHERE customer IN ('Gerald Garner','A+Maintenance');

SQL Results:
id
customer
day_of_order
product
quantity
3
A+Maintenance
2008-08-16 00:00:00.000
Hanging Files
14
4
Gerald Garner
2008-08-15 00:00:00.000
19" LCD Screen
5
The results provide a list of all customer orders made by each of the customer names we have listed ins
the IN clause ('Gerald Garner','A+Maintenance'). This is a great way to query for all orders made by a
handful of different customers as we can see everything these particular customers have ordered thus fa

The real power of this condition comes to life when used with a subquery that retrieves a list of values.
Running any SELECT query returns results in list format. And as we mentioned just a few short mome
ago, this list can then be passed as a list for the IN clause using a subquery.

Let's adjust the previous example to only retrieve only the products column, as opposed to retrieving al
columns (*).
SQL - Case
SQL CASE is a very unique conditional statement providing if/then/else logic for any ordinary SQL
command, such as SELECT or UPDATE. It then provides when-then-else functionality (WHEN this
condition is met THEN do_this).

Advertise on Tizag.com

This functionality provides the developer the ability to manipulate the presentation of the data without
actually updating or changing the data as it exists inside the SQL table.

SQL Select Case Code:


USE mydatabase;

SELECT product,
'Status' = CASE
WHEN quantity > 0 THEN 'in stock'
ELSE 'out of stock'
END
FROM dbo.inventory;

SQL Results:
product
Status
19" LCD Screen
in stock
HP Printer
in stock
Pen
in stock
Stapler
in stock
Hanging Files
in stock
Laptop
in stock
Using the CASE command, we've successfully masked the actual value of the product inventory withou
actually altering any data. This would be a great way to implement some feature in an online catalog to
allow users to check the status of items without disclosing the actual amount of inventory the store curr
has in stock.

SQL - Case: Real World Example


As a store owner, there might be a time when you would like to offer sale prices for products. This is a
perfect opportunity to write a CASE query and alter the inventory sale prices at the presentation level r
SQL - Group By
SQL GROUP BY aggregates (consolidates and calculates) column values into a single record value.
GROUP BY requires a list of table columns on which to run the calculations. At first, this behavior will
resemble the SELECT DISTINCT command we toyed with earlier.

Advertise on Tizag.com

SQL Group By:


USE mydatabase;

SELECT customer
FROM orders
GROUP BY customer;

SQL Results:
customer
A+Maintenance
Gerald Garner
Tizag
Here, SQL has consolidated like values and returned those that are unique. In this case, we have actuall
duplicated the behavior of SELECT DISTINCT, but you have also seen firsthand how GROUP BY acc
a table column as a list and consolidates like customer values.

To unleash the true power of GROUP BY, it is necessary to include at least one mathematical (aggregat
function, and to do so we will utilize the SUM() function to calculate how many total items have been
purchased by each of our customers.

SQL Code:
USE mydatabase;

SELECT customer, SUM(quantity) AS "Total Items"


FROM orders
GROUP BY customer;

SQL Results:
customer
Total Items
A+Maintenance
14
Gerald Garner
5
Tizag
SQL - Views
SQL VIEWS are data objects, and like SQL Tables, they can be queried, updated, and dropped. A SQL
VIEW is a virtual table containing columns and rows except that the data contained inside a view is
generated dynamically from SQL tables and does not physically exist inside the view itself.

Advertise on Tizag.com

SQL Create View Code:


CREATE VIEW virtualInventory
AS
SELECT * FROM inventory;

With a successful execution of this query, we have now created a view data object of the inventory tab
The virtualInventory view is considered a data object (like a table) and is now accessible to us the deve
Views can be queried exactly like any other SQL table.

SQL View Code:


USE mydatabase;

SELECT *
FROM virtualInventory;

SQL Results:
id
product
quantity
price
1
19" LCD Screen
25
179.99
2
HP Printer
9
89.99
3
Pen
78
0.99
4
Stapler
3
7.99
SQL - Dates
Date values are stored in date table columns in the form of a timestamp. A SQL timestamp is a record
containing date/time data, such as the month, day, year, hour, and minutes/seconds. It's not much differe
from the standard date format.

Advertise on Tizag.com

Date Columns:
Column Type
Format
time
HH:MM:SS
date
YYYY-MM-DD
datetime
YYYY-MM-DD HH:MM:SS
Date values are stored in the form of a timestamp, and SQL offers a built-in function called GETDATE
that returns the current date in the form of a SQL timestamp.

SQL SELECT GETDATE():


USE mydatabase;

SELECT GETDATE();

Timestamp Result:
2004-06-22 10:33:11.840
SQL expects dates to be formatted as above but does offer some flexibility when working with dates in
query statements. For instance, date values do not necessarily need to contain the hour, minutes, and se
values. SQL also accepts most traditional date formats such as "MM/DD/YY" (ex: "01/01/06").

Using a built in function, ISDATE() we can do some testing on date values to see if they meet the form
requirements.

SQL Code:
USE mydatabase;

SELECT
ISDATE('8/24/08') AS "MM/DD/YY",
ISDATE('2004-12-01') AS "YYYY/MM/DD";

ISDATE() returns a 1 or a 0 indicating a true or false result. In this case, both formats are acceptable da
SQL - Datepart
DATEPART() is a SQL function used to extract all kinds of date information from timestamps, and it is
function that is unique to Microsoft's SQL Server Application.

Advertise on Tizag.com

SQL Datepart:
USE mydatabase;

SELECT DATEPART(year, '2007-06-01') AS "Year";

SQL Results:
Year
2007
DATEPART() requires 2 parameters separated by a comma (,). The first parameter specifies what type
date data will be extracted, and the second parameter is a timestamp value.

SQL Datepart:
USE mydatabase;

SELECT DATEPART(year, '2007-06-01') AS "Year",


DATEPART(month, '2007-06-01') AS "Month",
DATEPART(day, '2007-06-01') AS "Day",
DATEPART(dayofyear, '2007-06-01') AS "DayofYear",
DATEPART(weekday, '2007-06-01') AS "Weekday";

SQL Results:
Year
Month
Day
DayofYear
Weekday
2007
6
1
152
6

Datepart Abbreviation Chart:


DatePart
Abbreviation
SQL - DateAdd()
DATEADD() is the SQL function used to add and increment date values. Hours, minutes, months, and
can be added to any date value. In fact, dates can be added based on any type of date part discussed in t
SQL DATEPART() lesson.

Advertise on Tizag.com

SQL Code:
USE mydatabase;

SELECT DATEADD(year, 1, getdate()) AS "+1 Year";

SQL Results:
+1 Year
2009-06-31 00:00:00.000
This example shows how to use DATEADD() to take a specified date value and increment it by the 'yea
date part. By replacing the middle parameter with a negative value, we can utilize the same DATEADD
function to subtract dates as well.

SQL Code:
USE mydatabase;

SELECT DATEADD(day,-1, '2006-06-01') AS "-1 Day";

SQL Results:
-1 Day
2006-05-31 00:00:00.000
In each example, SQL is able to perform a calculation on each date value based on a timestamp, and aft
the calculation, a timestamp value returned. Also note that the date parameter can be based on another S
function or the result of a subquery.

SQL Code:
USE mydatabase;

SELECT DATEADD(day,-30, (SELECT MAX(day_of_order) FROM orders)) AS "-30 Days";

SQL Results:
-30 Days
SQL - Delete Command(s)
In the SQL world, databases, rows, and columns all have one thing in common: once a DELETE statem
has been executed successfully against them, the data they once contained is lost forever! Be very caref
with these commands and be sure to properly backup all data before proceeding with any type of DELE
command(s).

Advertise on Tizag.com

SQL offers several ways to tackle data deletion. Here are the differences.

SQL Delete Commands:


DELETE - Deletes any number of rows from a data object.
DROP - Removes table columns, tables, and all data objects SQL applications.
TRUNCATE - Empties out data without removing the object itself.

SQL - Delete
DELETE queries work much like UPDATE queries and like UPDATE, it is much advised to always u
WHERE condition when running any delete query or else you risk deleting too much data.

SQL Delete Query:


USE mydatabase;

DELETE
FROM orders
WHERE customer = 'A+Maintenance';

SQL Results:
1 Row(s) affected

SQL - Truncate
SQL TRUNCATE is the fastest way to remove all data from a SQL table, leaving nothing but an empty
shell. You might choose to use this command when all the data inside of a table needs to be removed bu
you'd like the table column definitions to remain intact.

SQL Truncate Table Code:


USE mydatabase;

TRUNCATE TABLE orders;


SQL - Union
SQL UNION combines two separate SQL queries into one result set. A JOIN statement adds additiona
table columns to a result set (horizontally), UNION combines row results from one table with rows of
another table (vertically).

Advertise on Tizag.com

In order to perform a UNION the columns of table 1 must match those of table 2. This rule ensures that
result set is consistent as rows are fetched by SQL.

For these next exercises we suggest creating two different tables that are identical in structure but conta
unique rows of data. We challenge you to do this by reviewing the SQL Create queries and modifying t
to create two brand new employee tables.

SQL Select Union Code:


USE mydatabase;

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
SQL - Syntax - (Speaking SQL)
Syntax, by definition, means the study of linguistic rules and patterns. Every programming language,
including SQL, must follow a unique set of guidelines termed syntax. Punctuation, spaces, mathematic
operators, and special characters have special meaning when used inside of SQL commands and query
statements. For example, each and every SQL command will end with a semi colon (;).

Advertise on Tizag.com

Executing SQL commands that do not have proper syntax and formatting will result in a syntax error. S
errors might be the most common and first error messages new SQL developers will experience.

Let's now take a look at a very simple SQL command that will be used in just about every example
contained in this tutorial from here on out.

Sample SQL Command:


use mydatabase;

This command identifies a database as a target database, meaning that any SQL command or query exe
after this line will be run against the identified database. In this case, the database 'mydatabase' will be
target database. This is a good way to prevent mistakes and avoid potential data loss and a good reason
include this command into each and every authored SQL query.

SQL - Syntax: Capitalization and Spacing


In some programming languages, capitalizing commands or excessive spacing may or may not cause sy
code errors and cause the command to fail. SQL syntax is very loose when it comes to capitalization an
spacing, allowing a lot of room for the developer to decide on his/her own preference in regards to
capitalization and spacing.

Let's rewrite the same SQL command from the previous example and take advantage of SQL's loose sy
characteristics.

Sample SQL Command:


USE

mydatabase;

The example above, though it does look different due to the capitalization and spacing, will yield the sa
results as the first example.

SQL - Syntax: Building good habits


SQL - Data Types
SQL data takes shape in several different forms, including character strings, numbers, file stores, and d
SQL developers call the shots as to what types of data will be stored inside each and every table column
when creating a SQL table. The developer must specify the column type of each new SQL table column

Advertise on Tizag.com

Column types are synonymous with data types as the column type is what designates the type of data th
will be stored inside the column. In other words, a SQL data type is a label and a guideline for SQL to
understand what type of data is expected inside of each table column and this identifies how SQL will
interact with the stored data. Below, we will give you an overview on the types of data that can be store
within a SQL table.

SQL - Numbers, Decimals, and Dates


Data Types:
• Integers - (3, -17)
• Point(Decimal) - (3.23415)
• Date - (2004-06-22 10:33:11.840)

Storing numbers and decimals allows the developer to collect statistical data and create reports based o
data contained inside the table. SQL can even perform mathematical calculations against numeric data,
providing endless number-crunching abilities.

In SQL, decimals are often referred to as point or floating-point numbers. These data types are slightly
different from the normal 'integer' data types.

For the most part, date values are treated like numbers and they can even be added together and subtrac
offering the developer the option to add days, months, or years together to create new dates (more on th
later). Additionally, specific data can be extracted from date values, allowing the developer to pull spec
date information from a date value like only the month number, the year, or the day of the week.

SQL - Boolean Data


• ("TRUE" / "FALSE")
• (1/0)

Boolean values are true/false types of data. A Boolean table column will contain either string values of
"True" and "False" or the numeric equivalent representation, with 0 being false and 1 being true.

SQL - Character Strings


SQL - Expressions
SQL Expressions are the pieces of a SQL query that compare values against other values or perform
arithmetic calculations. Expressions can be found inside of any SQL command usually in the form of a
conditional statement. In the SQL world, conditional statements and expressions test or compare val
against other values.

Advertise on Tizag.com

SQL - Boolean Expressions


Boolean expressions return rows (results) when a single value is matched.

SQL Boolean Expression:


USE mydatabase;

SELECT * FROM orders WHERE id = '1';

SQL Results:
id
customer
day_of_order
product
quantity
1
Tizag
2008-08-01 00:00:00.000
Pen
4

SQL - Numeric Expression


Numeric Expressions return a single numeric value instead of an entire row and usually perform
calculations.

SQL Code:
USE mydatabase;

SELECT 15 + 4;

SQL Code:

You might also like