About Me

Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Thursday, 19 April 2012

SQL - Identifiers, Think SQL

SQL - Identifiers, Think SQL

As with any programming language, there are a few terms unique to SQL.


An Identifier is essentially a name of a database, table, or table column. As the creator of the database, you are free to identify these objects as you please; we merely suggest you keep these guidelines in mind when you do.
  • Develop your own unique naming scheme. -- Use terms that relate to one another and will be easy to recognize apart from your code.
  • Be conscious of how long your names become. -- Especially be aware when the time comes to name your columns.
  • Avoid names without meaning. -- Develop a working scheme that also has meaning behind the names.
  • Be consistent. -- If you capitalize one table name, capitalize each table name; if you choose to use abbreviations, make sure they do not have double meanings or ambiguous meaning.
Develop a clear, concise schema, and stick to it as your database develops.

SQL - Literals

Literal is a term for data types such as strings, numbers, or boolean values in SQL. These values are not named by you the programmer; they just exist.

Literal Breakdown:

string literals
'This is a string value'
'5893 Moon River Dr.'

number literals
823
-4.5
3.387920

boolean literals
TRUE
FALSE
1
0

SQL - Predicates

SQL - Predicates

SQL Predicates are found on the tail end of clauses, functions, and SQL expression inside of existing query statements. We've actually already covered a few SQL predicates already and most on this list should be familiar to you.

SQL Predicates:

AND
OR
LIKE
BETWEEN
AS
TOP(LIMIT)

SQL - Top

SQL Top is used to limit the number of results returned by a query. The top command is generally followed by a number that indicates the maximum number of results to return for a given query.

SQL Code:

use mydatabase;

SELECT TOP 2 *
FROM orders

SQL Results:

idcustomerday_of_orderproductquantity
1Tia2008-08-01 00:00:00.000Pen4
2Tia2008-08-01 00:00:00.000Stapler3

SQL - Structure

SQL - Structure

The importance of building your tables correctly could be considered its own form of art. Psychologists have even gone as far to say that those with the ability to organize their thoughts and concepts well tend to be absolutely brilliant (ie Mozart, Einstein, DaVinci). A database is only slightly different from the human brain and clear organization is a must, especially if large quantities of people will be using the same database.
Designing the right database has a lot to do with what you need to accomplish. A database with thousands and thousands or even millions of records requires a completely different solution than a database that will only have a few hundred records. Think about the future and plan ahead.

SQL - Table Relationships

The key to a large database is having tables with material that can relate to one another. A great example is the employee ID. Ever wonder or joke about being just another number to the company. A lot of that has to do with the way they set up their database. A large company is going to have a weekly payroll and a personal information table. They might be set up like the following:
personal_info
emp_idlast_namefirst_name
0056MynceGeorge
0097JenkinsFred
weekly_payroll
emp_idhoursrateofpay
005637.527.00
009744.522.25
This set up proves useful in several ways. The tables are smaller, more compact, and precise, allowing for maximum access speeds with each query. We can also moderate who has access to each table, meaning that our accountant can have access to the payroll table, but not the personal information table, eliminating security risks.
Relationship tables are the choice for high-traffic databases. There are countless security advantages, faster query returns, and complete view customization (more on this later).

SQL - Commands

SQL - Commands

SQL commands are lines of SQL code that ask the SQL application to perform simple tasks against with data inside of a database. Often we refer to commands as query statements or scripts; all of these terms are synonymous. Most of the commands and statements you will see in this tutorial are fairly standard and will work across multiple database applications despite the fact this tutorial is aimed for the SQL Server Express user.


SQL commands are declarative sentences or 'orders' executed against a SQL database. The typical command is comprised of several different components including clauses, functions, expressions, or objects but the only required components are a SQL Clause and the data object (a database or a database table).

SQL - Clauses

A SQL clause is the word or phrase that begins each SQL command statement and the single most important component to any SQL command. Looking at the clause of any given SQL command usually tells the SQL programmer what that particular command intends to do to the database. For instance, a SELECT command begins with the SELECT clause and any level of SQL programmer will recognize the SELECT query as a command selecting data from the database.
Other SQL clauses include:
  • Add
  • Drop
  • Create
  • Insert
  • Select
  • Update
  • Replace
  • Delete

SQL - Sample Commands

SQL Code:

SELECT getdate(); -- Selects the current (server) date and time.

CREATE DATABASE MyDatabase; -- Creates a database named Mydatabase;

INSERT INTO orders 
 -- Inserts data into a database table
VALUES('A+Maintenance','8/16/08','Hanging Files',12);

SQL - Platforms Applications

SQL - Platforms Applications

There are many, many different SQL applications in existence. A handful of platforms are available for free and are the preferred choice among individuals and small businesses. Other SQL platforms are designed with enterprise level customers in mind and are much more expensive.

SQL Applications:

  • IBM's DB2
  • MySQL
  • PostgreSQL
  • Oracle
  • Microsoft's SQL Server

SQL - MySQL and PostgreSQL

MySQL and PostgreSQL are open source database programs rich in functionality and flexibility. They are often the choice of web developers and small businesses simply because they are light-weight and are offered at the right price: free. Most open source software will also work across multiple different operating systems, which is yet another benefit to small businesses.

SQL - SQL Server

Microsoft's SQL Server is steadily on the rise in the commercial world gaining popularity slowly. This platform is only available to Windows users at this time, but offers its users very user-friendly interface that is great for beginning SQL developers. A free trial version can be downloaded at the Microsoft website.

SQL - DB2 and Oracle

By far the selection of choice for large corporations is either Oracle or DB2. Companies that have large ties to IBM stick to their DB2 software whereas others have made the switch to Oracle. These systems run on personal computers as well as large corporate mainframes and are ideal for processing vast amounts of data at the enterprise level.

SQL - Historical Information

SQL - Historical Information

In the '60's database software required the use of complex mainframe machines that were difficult to maintain and run. Information technologists worked around the clock monitoring, updating, and manually uncorrupting these machines.


Each mainframe ran different software from different manufacturers. IBM pulled ahead in software development internationally with efforts of software aimed at database management. The problem was that each mainframe ran a different type of "language".
Enter SQL, the new standard for any database program: Structured Query Language. SQL bridged the barriers between mainframes and allowed large corporations to network their efforts. SQL was introduced in the 1970's and quickly gained international popularity. SQL allows a programmer to tell a program exactly what data to retrieve and how to display it.

SQL - Under Development

Software at the time was still underdeveloped and several continuous problems plagued database storage. Transactions happening at the same time were often combined, mixed together, or even lost altogether. For instance, say two individuals made a deposit at exactly the same time from two different locations. The software was unable to cope with this, and their bank transactions were completely switched. Suzy deposited $10,000 while Joe withdrew $15. Because of the faulty software Joe's withdrawal was posted on Suzy's account and Suzy's deposit was posted to Joe's account.
Along came Relational Database Management Systems (RDBMS). This software is still being used and is quite powerful. Relational databases allow developers to build relationships between databases and tables. This provides tremendous opportunities for data management and is still the favorite software used today. MySQL, SQL Server, DB2, and Oracle are all RDBMSs, and each have a substantial hold in the market share to this day.

SQL - Expressions

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 values against other values.

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:

idcustomerday_of_orderproductquantity
1Tizag2008-08-01 00:00:00.000Pen4

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:

USE mydatabase;

SELECT (15 / 5) * 10;

SQL Code:

USE mydatabase;

SELECT ((5+5) * (5+5));
Each of the examples above returns a numeric value which is displayed inside the results pane of the SQL application. SQL also offers several built-in functions to perform what is known as aggregate data calculations against a table or a specific table column.
  • AVG() -- Returns the average value of a stated column.
  • COUNT(*) -- Returns a count of the number of rows of table.
  • SUM() -- Returns the sum of a given column.
Using one of the following functions also returns a numeric value:

SQL Code:

USE mydatabase;

SELECT COUNT(*) AS "Number of Orders"
FROM orders;

SQL Code:

USE mydatabase;

SELECT SUM(quantity)AS "Total Number of Items Purchased"
FROM orders;

SQL Code:

USE mydatabase;

SELECT AVG(quantity) AS "Average Number of Items Purchased"
FROM orders;
We can also combine these queries into a single query so that the results are viewable all at once.

SQL Code:

USE mydatabase;

SELECT COUNT(*) AS "Number of Orders",
SUM(quantity)AS "Total Number of Items Purchased",
AVG(quantity)AS "Average Number of Items Purchased"
FROM orders;

SQL - Date Expressions

As the name suggests, Date Expressions return date/time values.
  • GetDate() -- Returns the current date/time.
  • Current_Timestamp -- Returns the current timestamp.
Date expressions as you may have guessed, return date values. We will be taking a closer look at date expressions later on in this tutorial. Stay tuned.

SQL Code:

USE mydatabase;

SELECT Current_Timestamp;
SELECT  GETDATE();

SQL - Data Types

SQL - Data Types

SQL data takes shape in several different forms, including character strings, numbers, file stores, and dates. 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.


Column types are synonymous with data types as the column type is what designates the type of data that 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 stored 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 on the 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 subtracted offering the developer the option to add days, months, or years together to create new dates (more on this later). Additionally, specific data can be extracted from date values, allowing the developer to pull specific 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

Character Strings:

  • VARCHAR - ('Words or numbers')
  • Text - ('Once upon a time...')
Strings range from a single word or character to large blocks of text including multiple paragraphs and unique symbols. Set the table column type to VARCHAR or Text in order to incorporate string data types into SQL tables.

SQL Server Table Column Types:

bigintInteger value (-9,223,372,036,854,775,808 - 9,223,372,036,854,775,807)2^63
intsmaller Integer value (-2,147,483,648) - (2,147,483,647)2^31
smallintsmaller Integer value (-32,768) - (32,767)2^15
tinyintsmaller Integer values 0 - 2552^8
bitInteger data value (either 1 or 0 value)1 or 0
decimalDecimal values from -10^38 - 10^3810^38
numericDecimal values from -10^38 - 10^3810^38
moneyMoney values (-922,337,203,685,477.5808) - (922,337,203,685,477.5807)2^63
smallmoneySmaller Money Values (-214,748.3648) - (214,748.3647)2^31
datetimeDate value (January 1, 1753) - (December 31, 9999)
smalldatetimeSmaller Date Value (January 1, 1900) - (June 6, 2079)
timestampUnique Number Value (updates when row is updated)
charCharacter String Value (max 8,000 characters)
varcharCharacter String Value maximum of 8,000 characters, unless otherwise noted)
ncharCharacter String Value (max 4,000 characters)
nvarcharCharacter String Value (max 4,000 characters)
textCharacter String Value (max 2,147,483,647 characters)2^31
ntextCharacter String Value (max 1,073,741,823 characters)2^30
binaryBinary Value (max 8,000 bytes)
varbinaryBinary Value (max 8,000 bytes)
imageBinary Value (max 2,147,483,647 bytes)2^31
uniqueidentifierGlobal Unique ID (GUID)

SQL - Defaults and Null Values

NULL values are 'nothing' values. When a value is null, it means the value is empty and contains no value -- not even '0'. NULLs are unique data types that are usually the default setting for all table columns. When a SQL developer runs across a NULL value in a database, it is generally an indication that this value is either new or has not been modified.
The SQL developer may specify to allow or disallow the NULL values eliminating the possibility of running across 'empty' table columns when creating a SQL table. If the developer chooses not to allow NULL values he/she may specify a custom default value instead of the NULL (nothing) value. Primary Key table columns do not allow NULL values since this column's sole purpose is to be the unique identifier for a table column. Having a NULL unique identifier would be similar to having a car license plate that is blank.
By default, NULL values are allowed on all newly created table columns meaning a table column is allowed to be 'empty', except primary key columns. A NULL value is a special type of value that can be tested for by most programming languages including SQL and can provide the developer a means to 'test' and see if data exists or has been modified. As a new programmer you may not fully understand the benefits a NULL value can bring, but with experience, you will learn to hate/appreciate them.

SQL - Syntax - (Speaking SQL)

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, mathematical 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 (;).

Executing SQL commands that do not have proper syntax and formatting will result in a syntax error. Syntax 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 executed after this line will be run against the identified database. In this case, the database 'mydatabase' will be the target database. This is a good way to prevent mistakes and avoid potential data loss and a good reason to 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 syntax code errors and cause the command to fail. SQL syntax is very loose when it comes to capitalization and 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 syntax characteristics.

Sample SQL Command:

USE


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

SQL - Syntax: Building good habits

While coding in any language, it is important to develop good, consistent habits and maintain clean code. Clean code allows another SQL developer to step right in where you have left off without missing a beat. A developer with diligent coding habits will prevent many syntax errors before executing his/her scripts and also will be able to detect possibly syntax problems before they cause problems in a SQL Command.
Good habits include:
  • Consitency
  • Clean and Concise
  • Use of Comments (more on this later)
  • Scalability
Coding in any language is as much of an art form as authoring best selling novels and stories. Take pride in doing so and always do your best to follow good coding habits.

SQL - Union

SQL - Union

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


In order to perform a UNION the columns of table 1 must match those of table 2. This rule ensures that the 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 contain unique rows of data.

SQL Select Union Code:

USE mydatabase;

SELECT * FROM employees
UNION
SELECT * FROM employees2;

SQL Table:

IDLastnameFirstnameTitle
1JohnsonDavidcrew
2HivelyJessicacrew
9HicksFreddycrew
10HarrisJoelcrew
11DavisJuliemanager
101YazzowJimcrew
102AndersonCraigcrew
103CarlsonKevincrew
104MainesBradcrew
The result is a complete listing of every employee from the two tables, perhaps representing a list of employees from two different departments.
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:

LastnameFirstnameSalePrice
JohnsonDavidHOT DOG1.99
HivelyJessicaLG SFT DRK1.49
DavisJulieCK SLD3.99
YazzowJimHOT DOG1.99
CarlsonKevinLG SFT DRK1.49
Here we combined a join query with the union clause to create one table.

SQL - Union All

UNION ALL selects all rows from each table and combines them into a single table. The difference between UNION and UNION ALL is that UNION ALL will not eliminate duplicate rows. Instead, it just pulls all rows from all tables fitting your query specifics and combines them into a table.

SQL Code:

SELECT * FROM employees
UNION ALL
SELECT * FROM employees2;

SQL Table:

IDLastnameFirstnameTitle
1JohnsonDavidcrew
2HivelyJessicacrew
9HicksFreddycrew
10HarrisJoelcrew
11DavisJuliemanager
101YazzowJimcrew
102AndersonCraigcrew
103CarlsonKevincrew
11DavisJuliemanager
104MainesBradcrew

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:

LastnameFirstnameSalePrice
JohnsonDavidHOT DOG1.99
HivelyJessicaLG SFT DRK1.49
DavisJulieCK SLD3.99
11DavisJuliemanager
YazzowJimHOT DOG1.99
CarlsonKevinLG SFT DRK1.49
11DavisJuliemanager
11DavisJuliemanager

SQL - Delete Command(s)

SQL - Delete Command(s)

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


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 use a 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 but you'd like the table column definitions to remain intact.

SQL Truncate Table Code:

USE mydatabase;

TRUNCATE TABLE orders;
NOTE: Executing the command above will empty your table data and you will lose this data forever! If you plan on following along do not execute this query.

SQL - Drop

SQL DROP is another command that removes data from the data store. The DROP command must be performed on SQL objects including databases, tables, table columns, and SQL views. Dropping any of these objects removes them completely from your SQL application and all data contained in any of the data objects dropped are lost forever.

SQL Drop Examples:

USE mydatabase;

DROP TABLE orders;
DROP DATABASE mydatabase;
DROP VIEW viewname;
DROP INDEX orders.indexname;

-- FOR USE WITH ALTER COMMANDS
DROP COLUMN column_name
DROP FOREIGN KEY (foreign_key_name)
The above example also includes the syntax to drop table columns and foreign keys. These items are outlined in the SQL ALTER lesson.

SQL - DateAdd()

SQL - DateAdd()

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

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 'year' 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 after the calculation, a timestamp value returned. Also note that the date parameter can be based on another SQL 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
2008-07-17 00:00:00.000
Here we have now constructed a very useful, dynamic statement pulling the most current order (MAX) in the orders table, and we've been able to subtract one day from that value. While this information does not directly prove useful, if we take this query one step further and place this statement in a WHERE as a subquery, we should be more satisfied with the results.

SQL Code:

USE mydatabase;

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

SQL Results:

idcustomerday_of_orderproductquantity
1Tia2008-08-01 00:00:00.000Hanging Files11
2Tia2008-08-01 00:00:00.000Stapler3
3A+Maintenance2008-08-16 00:00:00.000Hanging Files 14
4Gerald Garner2008-08-15 00:00:00.00019" LCD Screen5
5Tia2008-07-25 00:00:00.00019" LCD Screen5
6Tia2008-07-25 00:00:00.000HP Printer4
By placing this calculated date in the WHERE clause, we were able to pull all the records that have happened within 30 days of the most recent order (2008-07-17 00:00:00.000). We are able to query the orders table and request this information with a dynamic query that will yield different results as new orders are placed and time goes by.

SQL - Datepart

SQL - Datepart

DATEPART() is a SQL function used to extract all kinds of date information from timestamps, and it is a function that is unique to Microsoft's SQL Server Application.

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 of 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:

YearMonthDayDayofYearWeekday
2007611526

Datepart Abbreviation Chart:

DatePartAbbreviationExample
yearyy, yyyyDATEPART(yy, getdate())
quarterqq, qDATEPART(qq, getdate())
monthmm, mDATEPART(mm, getdate())
dayofyeardy, yDATEPART(dy, getdate())
daydd, dDATEPART(dd, getdate())
weekwk, wwDATEPART(wk, getdate())
weekdaydwDATEPART(dw, getdate())
hourhhDATEPART(hh, getdate())
minutemiDATEPART(mi, getdate())
secondssDATEPART(ss, getdate())
millisecondmsDATEPART(ms, getdate())

Wednesday, 18 April 2012

SQL - Dates

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 different from the standard date format.

Date Columns:

Column TypeFormat
timeHH:MM:SS
dateYYYY-MM-DD
datetimeYYYY-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 inside query statements. For instance, date values do not necessarily need to contain the hour, minutes, and seconds 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 formatting 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 date formats as a 1 value was returned.

SQL - Month(), Day(), Year()

The Month(), Day() and Year() functions all extract corresponding values from a given date.

SQL Year():

USE mydatabase;

SELECT YEAR(GETDATE()) as "Year";
SELECT YEAR('8/14/04') as "Year";

SQL Month():

USE mydatabase;

SELECT MONTH(GETDATE()) as "Month";
SELECT MONTH('8/14/04') as "Month";

SQL Day():

USE mydatabase;

SELECT DAY(GETDATE()) as "Day";
SELECT DAY('8/14/04') as "Day";
Understanding timestamps and extracting pieces of dates is the first step in being able to perform date calculations and work more in-depth with SQL Dates.

SQL - Views

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.

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 table. The virtualInventory view is considered a data object (like a table) and is now accessible to us the developer. Views can be queried exactly like any other SQL table.

SQL View Code:

USE mydatabase;

SELECT *
FROM virtualInventory;

SQL Results:

idproductquantityprice
119" LCD Screen25179.99
2HP Printer989.99
3Pen780.99
4Stapler37.99
5Hanging Files3314.99
6Laptop16499.99
Even though a SQL VIEW is treated like a data object in SQL, no data is actually stored inside of the view itself. The view is essentially a dynamic SELECT query, and if any changes are made to the originating table(s), these changes will be reflected in the SQL VIEW automatically.

SQL Code:

USE mydatabase;

UPDATE inventory
SET price = '1.29'
WHERE product = 'Pen';
Execute the following query to verify the results:

SQL Verification Query Code:

USE mydatabase;

SELECT *
FROM virtualInventory
WHERE product = 'Pen';

SQL Results:

idproductquantityprice
3Pen781.29

SQL - Drop View

Views can also be removed by using the DROP VIEW command.

SQL Drop View:

USE mydatabase;

DROP VIEW virtualInventory;

SQL - Group By

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.

SQL Group By:

USE mydatabase;

SELECT customer
FROM orders
GROUP BY customer;

SQL Results:

customer
A+Maintenance
Gerald Garner
Tia
Here, SQL has consolidated like values and returned those that are unique. In this case, we have actually duplicated the behavior of SELECT DISTINCT, but you have also seen firsthand how GROUP BY accepts 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 (aggregate) 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:

customerTotal Items
A+Maintenance14
Gerald Garner5
Tia23
With the addition of the aggregate SUM() function, we've let SQL calculate how many products have been ordered by each customer and returned them for viewing with a single query statement.
Taking a look at another example, we can also figure out how many of each product was ordered with the use of a single query statement.

SQL Code:

USE mydatabase;

SELECT product, SUM(quantity) AS "Total Items"
FROM orders
GROUP BY product;

SQL Results:

productTotal Items
19" LCD Screen10
Hanging Files25
HP Printer4
Stapler3
GROUP BY would also be a great way to calculate how much total cash of our customers has spent. Let's take a look at what that query may look like.

SQL Code:

USE mydatabase;

SELECT customer,
  SUM((orders.quantity * inventory.price)) AS "COST"
FROM orders
JOIN inventory
ON orders.product = inventory.product
GROUP BY customer;

SQL Results:

productCOST
A+Maintenance209.86
Gerals Garner899.95
Tia1448.77

SQL - Grouping By Multiple Columns

Like the ORDER BY clause, GROUP BY can accept a list of table columns on which to group by.

SQL Code:

USE mydatabase;

SELECT day_of_order,
  product,
  SUM(quantity) as "Total"
FROM orders
GROUP BY day_of_order,product
ORDER BY day_of_order;

SQL Results:

day_of_orderproductTotal
2008-07-25 00:00:00.00019" LCD Screen5
2008-07-25 00:00:00.000HP Printer4
2008-08-01 00:00:00.000Hanging Files11
2008-08-01 00:00:00.000Stapler3
2008-08-15 00:00:00.00019" LCD Screen5
2008-08-16 00:00:00.000Hanging Files14
This query will group together and sum the total number of products purchased on any given date, regardless of what customer has purchased the item. It's a very useful query to keep in mind.

SQL - Having

The SQL HAVING clause is "like a WHERE clause for aggregated data." It's used with conditional statements, just like WHERE, to filter results. One thing to note is that any column name appearing in the HAVING clause must also appear in the GROUP BY clause.

SQL Having:

USE mydatabase;

SELECT day_of_order,
  product,
  SUM(quantity) as "Total"
FROM orders
GROUP BY day_of_order,product,quantity
HAVING quantity > 7
ORDER BY day_of_order;

SQL Results:

day_of_orderproductTotal
2008-08-01 00:00:00.000Hanging Files11
2008-08-16 00:00:00.000Hanging Files14
The quantity column is now considered aggregated in SQL terms, because its values have been summed together using the SUM() function. In the example above, HAVING acts as the WHERE clause for aggregate values, filtering out results that do not meet the condition (quantity > 7).

SQL - Case

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).


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:

productStatus
19" LCD Screenin stock
HP Printerin stock
Penin stock
Staplerin stock
Hanging Filesin stock
Laptopin stock
Using the CASE command, we've successfully masked the actual value of the product inventory without 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 currently 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 rather than actually changing the price inside of the inventory table. CASE provides a way for the store owner to mask the data but still present it in a useful format.
Let's back up a second and pull a listing of our recent orders and join this with the inventory table so that the results contain both the quantity of items purchased and the price from the inventory table. To accomplish this we will need to first write a SQL JOIN query.

SQL Join Query:

USE mydatabase;

SELECT dbo.orders.id,
  dbo.orders.customer,
  dbo.orders.quantity,
  dbo.inventory.product,
  dbo.inventory.price
FROM orders
JOIN inventory
ON orders.product = inventory.product
In order to provide results that are much clearer, we've moved away from selecting every column with (*). Instead, we've listed each column that will be of use for the next few steps. Also, let's plan on offering a 25% off sale on these items.

SQL Results:

idcustomerquantityproductprice
1Tia11Hanging Files14.99
2Tia3Stapler7.99
3A+Maintenance14Hanging Files14.99
4Gerald Garner519" LCD Screen179.99
5Tia519" LCD Screen179.99
6Tia4HP Printer89.99
Next we need to look at reducing the prices of the items according to our sale price. For the purpose of this exercise, let's offer a 25% discount on all our currently pending orders using a SQL CASE query.

SQL Select Case Code:

USE mydatabase;

SELECT dbo.orders.id,
  dbo.orders.customer,
  dbo.orders.quantity,
  dbo.inventory.product,
  dbo.inventory.price,
 'SALE_PRICE' = CASE
   WHEN price > 0 THEN (price * .75)
          END
FROM orders 
JOIN inventory
ON orders.product = inventory.product
Multiplying the current price by .75 reduces the price by approximately 25%, successfully applying the changes we would like to see but doing so without actually changing any data.

SQL Results:

idcustomerquantityproductpriceSALE_PRICE
1Tia11Hanging Files14.9911.2425
2Tia3Stapler7.995.9925
3A+Maintenance14Hanging Files14.9911.2425
4Gerald Garner519" LCD Screen179.99134.9925
5Tia519" LCD Screen179.99134.9925
6Tia4HP Printer89.9967.4925
The results speak for themselves as the records returned indicate a new table column with the calculated sales price now listed at the end of each row.
Since SQL CASE offers a conditional statement (price > 0), it wouldn't take much more effort to create some conditional statements based on how many products each customer had ordered and offer different discounts based on the volume of a customer order.
For instance, as a web-company, maybe we would like to offer an additional 10% discount to orders totaling more than $100. We could accomplish this in a very similar fashion.

SQL Results:

USE mydatabase;

SELECT dbo.orders.id,
  dbo.orders.customer,
  dbo.orders.quantity,
  dbo.inventory.product,
  dbo.inventory.price,
 'SALE_PRICE' = CASE
 WHEN (orders.quantity * price) > 100 THEN (price * .65)
 ELSE (price * .75)
        END
FROM orders 
JOIN inventory
ON orders.product = inventory.product

:

idcustomerquantityproductpriceSALE_PRICE
1Tia11Hanging Files14.999.7435
2Tia3Stapler7.995.9925
3A+Maintenance14Hanging Files14.999.7435
4Gerald Garner519" LCD Screen116.9935134.9925
5Tia519" LCD Screen179.99116.9935
6Tia4HP Printer89.9958.4935
With this query, we have now successfully reduced all orders by 25% and also applied an additional 10% discount to any order totaling over $100.00.
In each of the examples above, SQL CASE has been utilized to perform presentation level adjustments on data values and its versatility provides limitless results.

SQL - In

SQL - In

SQL IN is an operator used to pull data matching a list of values. A scenario where this proves useful would be if we wanted to retrieve customer data for two or more customers. We can use the IN operator to specify a list of customer names, and SQL will retrieve rows reflecting every customer in the list.


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

SQL In:

USE mydatabase;

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

SQL Results:

idcustomerday_of_orderproductquantity
3A+Maintenance2008-08-16 00:00:00.000Hanging Files 14
4Gerald Garner2008-08-15 00:00:00.00019" LCD Screen5
The results provide a list of all customer orders made by each of the customer names we have listed inside 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 far.
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 moments 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 all columns (*).

SQL In:

USE mydatabase;

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

Results:

product
Hanging Files
19" LCD Screen
Our results represent a query run to achieve a list of products sold to two of our customers. Now let's convert this query to a subquery and use this query as an input list to check the inventory table to see if we have any of these items in stock.

SQL In:

USE mydatabase;

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

SQL Results:

idproductinventoryprice
119" LCD Screen25179.99
5Hanging Files3314.99
By specifying a sub query as our list of values we were able to take advantage of the relationship our tables have with each other and create a very dynamic query. This query saves us the time of scrolling through the entire inventory table and checking the stock of each item purchased by any of our recent customers.

SQL - Not In

SQL NOT IN, as you may have guessed, allows the developer to eliminate a list of specific values from the result set.

SQL Not In:

USE mydatabase;

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

SQL Results:

idproductquantityprice
2HP Printer989.99
3Pen780.99
4Stapler37.99
6Laptop16499.99

SQL - Join

SQL - Join

SQL JOIN joins together two tables on a matching table column, ultimately forming one single temporary table. The key word here is temporary. The tables themselves remain intact, and running a JOIN query does not in any way change the data or table structure. JOIN is another way to select specific data from two or more relational tables.


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:

idcustomerday_of_orderproductquantityidproductquantityprice
1Tia2008-08-01 00:00:00.000Hanging Files115Hanging Files3314.99
2Tia2008-08-01 00:00:00.000Stapler34Stapler37.99
3A+Maintenance2008-08-16 00:00:00.000Hanging Files145Hanging Files3314.99
4Gerald Garner2008-08-15 00:00:00.00019" LCD Screen5119" LCD Screen25179.99
5Tia2008-07-25 00:00:00.00019" LCD Screen5119" LCD Screen25179.99
6Tia2008-07-25 00:00:00.000HP Printer42HP Printer989.99
The line beginning with JOIN (Line 4) is where we tell SQL which table we would like to join. The next line (Line 5) is a different story. Here is where we have specified the condition to JOIN ON. In this case, both tables have identical product columns which makes them an ideal target for a join. Basically we are temporarily merging the tables connecting them where they match, the product column.
This type of join matches values from one table column with a corresponding value in another table and uses that match to merge the tables together. In our make-believe store world, this let's us join the inventory table with the orders table to show us all the items we currently have in stock for our customers and also the price of each item.
Let's rework this query a bit and strip away a few of the table columns to make our results easier to read and understand. We will replace the (*) parameter with a list containing only the table columns we are interested in viewing.

SQL Join:

USE mydatabase;

SELECT orders.customer,
orders.day_of_order,
orders.product,
orders.quantity as number_ordered,
inventory.quantity as number_instock,
inventory.price
FROM orders
JOIN inventory
ON orders.product = inventory.product

SQL Results:

customerday_of_orderproductnumber_orderednumber_instockprice
Tia2008-08-01 00:00:00.000Hanging Files113314.99
Tia2008-08-01 00:00:00.000Stapler337.99
A+Maintenance2008-08-16 00:00:00.000Hanging Files143314.99
Gerald Garner2008-08-15 00:00:00.00019" LCD Screen525179.99
Tia2008-07-25 00:00:00.00019" LCD Screen525179.99
Tia2008-07-25 00:00:00.000HP Printer4989.99
Since we have one column in each table named the same thing (quantity), we used AS to modify how these columns would be named when our results were returned. These results should be more satisfying and easier to read now that we have removed some of the unnecessary columns.

SQL - Right Join

RIGHT JOIN is another method of JOIN we can use to join together tables, but its behavior is slightly different. We still need to join the tables together based on a conditional statement. The difference is that instead of returning ONLY rows where a join occurs, SQL will list EVERY row that exists on the right side, (The JOINED table).

SQL - Right Join:

USE mydatabase;

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

SQL Results:

idcustomerday_of_orderproductquantityidproductquantityprice
4Gerald Garner2008-08-15 00:00:00.00019" LCD Screen5119" LCD Screen25179.99
5Tia2008-07-25 00:00:00.00019" LCD Screen5119" LCD Screen25179.99
6Tia2008-07-25 00:00:00.000HP Printer42HP Printer989.99
NULLNULLNULLNULLNULL3Pen780.99
2Tia2008-08-01 00:00:00.000Stapler34Stapler37.99
1Tia2008-08-01 00:00:00.000Hanging Files115Hanging Files3314.99
3A+Maintenance2008-08-16 00:00:00.000Hanging Files145Hanging Files3314.99
NULLNULLNULLNULLNULL6Laptop16499.99
You should see a new row at the bottom of the results box with a bunch of NULL values. This is a result of the RIGHT JOIN and is the intended result from running the query. We end up with an extra row because inside of the inventory table, the Laptop item was not joined with a product from the orders table. This just means that we have not sold a laptop as of yet and it shouldn't be much a surprise since we already know from querying the orders table in previous lessons that there have been no laptop orders so far.
By specifying RIGHT JOIN, we have told SQL to join together the tables even if no matches are found in the conditional statement. All records that exist in the table on the right side of the conditional statement (ON orders.product = inventory.product) will be returned and NULL values will be placed on the left if no matches are found.

SQL - Left Join

SQL LEFT JOIN works exactly the same way as RIGHT JOIN except that they are opposites. NULL values will appear on the right instead of the left and all rows from the table on the left hand side of the conditional will be returned.
Unfortunately, we will not be able to show a very intuitive example of a LEFT JOIN because of how our tables are structured. The orders table should always have a matching inventory item and if not, that means we are in big trouble as we could be selling items we do not carry in inventory. For good measure, here's what a LEFT JOIN would look like:

SQL Left Join:

USE mydatabase;

SELECT *
FROM orders
LEFT JOIN inventory
ON orders.product = inventory.product
SQL JOIN is intended to bring together data from two tables to form a single larger table, and often, it will paint a more detailed picture of what the data represents. By merging these two data sets, we were able to peer into our database and ensure that each item ordered so far is in stock and ready to be shipped to our customers.

SQL - Subqueries

SQL - Subqueries

Subqueries are query statements tucked inside of query statements. Like the order of operations from your high school Algebra class, order of operations also come into play when you start to embed SQL commands inside of other SQL commands (subqueries). Let's take a look at a real world example involving the orders table and figure out how to select only the most recent order(s) in our orders table.

To accomplish this, we are first going to introduce a built-in SQL function, MAX(). This function wraps around a table column and quickly returns the current highest (max) value for the specified column. We are 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 to our little dilemma.

SQL Select Subquery Code:

USE mydatabase;

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

:

idcustomerday_of_orderproductquantity
3A+Maintenance2008-08-16 00:00:00.000Hanging Files 14
This query is a dynamic query as it pulls current information and will change if a new order is placed. Utilizing a subquery we were able to build a dynamic and robust solution for providing us with current order information.