sql- lokesh verma

50
sql - (pronounced " sequel  " ) SQL stands for Structured Query Language, and it 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 bit longer. sql - fundamentals Some of the basic functions of SQL are inputting, modifying, and dropping data from databases. In this tutorial, we use command line examples to give you an idea of what SQL is capable of. Coupled with the use of web languages such as HTML and PHP, S QL becomes an even greater tool for building dynamic web applications. sql - tutorial scope Reading further, you will encounter a number of hands-on examples intended to introduce you to SQL. The majority of these examples are intended to span ac ross the different available variations of SQL, but the primary focus of this tutorial is Microsoft's SQL Server Express. sql - getting started To get started, you will need to install Microsoft SQL Server Express. For installation help, we suggest you go straight to the developer homepage: SQL Server Express Download: SQL Server It is preferred that you select SQL Server Express 2008 for this tutorial. This version of SQL is available for private use for free, and we've provided the link to Microsoft's site, or you can find the download page by se arching for "SQL Server Express" on Google. Follow the online installation guide that Microsoft provides, and launch SQL S erver Management Studio Express to connect to your SQL database. This Management Studio Application will be your temporary home for the remainder of the tutorial. sql - world wide web Building a website on SQL architecture is quickly becoming the standard among web 2.0 sites. With a SQL backend, it is fairly simple to store user data, email lists, or other kinds of dynamic data. E -Commerce web sites, community sites, and online web services rely on SQL databases to manage user data or process user purchases. SQL has become popular among web developers due to its flexibility and simplicity. With some basic knowledge of HTML, PHP, and a database program such as Microsoft's SQL Server, a developer becomes capable of creating complex websites and applications while relying on online web s ervices to provide a SQL backend in which user data is stored. This tutorial will provide you with just a small taste of this type of programming and architecture. sql - databases What's a Database? A SQL database is nothing more than an empty shell, like a vac ant warehouse. It offers no real functionality whatsoever, but does provide a virtual space to store d ata. Data is stored inside of database objects calledtables, and tables are the containers that actually hold specific types of data, such as numbers, files, strings, and dates.

Upload: lokesh-verma

Post on 06-Apr-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 1/49

sql - (pronounced "sequel ")

SQL stands for Structured Query Language, and it is a very powerful and diverse language used to create andquery databases. Its loose syntax makes it easy to learn, but mastering its intricate architecture may take a bit longer.

sql - fundamentalsSome of the basic functions of SQL are inputting, modifying, and dropping data from databases. In this tutorial,

we use command line examples to give you an idea of what SQL is capable of. Coupled with the use of weblanguages such as HTML and PHP, SQL becomes an even greater tool for building dynamic web applications.

sql - tutorial scope

Reading further, you will encounter a number of hands-on examples intended to introduce you to SQL. Themajority of these examples are intended to span across the different available variations of SQL, but the primaryfocus of this tutorial is Microsoft's SQL Server Express.

sql - getting startedTo get started, you will need to install Microsoft SQL Server Express. For installation help, we suggest you go

straight to the developer homepage:

SQL Server Express Download:SQL Server 

It is preferred that you select SQL Server Express 2008 for this tutorial. This version of SQL is available forprivate use for free, and we've provided the link to Microsoft's site, or you can find the download page by searchingfor "SQL Server Express" on Google.

Follow the online installation guide that Microsoft provides, and launch SQL Server Management Studio Express

to connect to your SQL database. This Management Studio Application will be your temporary home for theremainder of the tutorial.

sql - world wide web

Building a website on SQL architecture is quickly becoming the standard among web 2.0 sites. With a SQLbackend, it is fairly simple to store user data, email lists, or other kinds of dynamic data. E-Commerce web sites,community sites, and online web services rely on SQL databases to manage user data or process user purchases.

SQL has become popular among web developers due to its flexibility and simplicity. With some basic knowledgeof HTML, PHP, and a database program such as Microsoft's SQL Server, a developer becomes capable of creatingcomplex websites and applications while relying on online web services to provide a SQL backend in which user datais stored. This tutorial will provide you with just a small taste of this type of programming and architecture.

sql - databases

What's a Database? A SQL database is nothing more than an empty shell, like a vacant warehouse. It offers noreal functionality whatsoever, but does provide a virtual space to store data. Data is stored inside of databaseobjects calledtables, and tables are the containers that actually hold specific types of data, such as numbers, files,strings, and dates.

Page 2: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 2/49

A single database can house hundreds of tables containing more than 1,000 table columns each and they maybe jam packed with relational data ready to be retrieved by SQL. Perhaps the greatest feature SQL offers is that itdoesn'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 ServerManagement Studio Express application, simply right-clicking on the Databases folder of the Object Explorer givesyou 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 ObjectExplorer pane.

Pressing this button offers an empty tab. All SQL query statements (code) that we will be exploring will beentered 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 querystatement 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 wascreated successfully. If you receive an error message instead, Google the error message for troubleshooting advice.(Vista users must verify that they are running SQL Server Management Studio Express with administrator privileges.)

Page 3: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 3/49

Congratulations! You have executed your first SQL command and written what is perhaps your first bit of SQLcode.

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 andschema are concepts far above the scope of this tutorial, we plan on diving in just past the surface to give you aglimpse 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 differenttypes of data, like numbers, texts, dates, and even files. There are many different types of table columns andthese data types vary, depending on how the SQL table has been created by the SQL developer. A table row is ahorizontal 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 tablewill serve as a practice table and we will begin to populate this table with some data which we can then manipulate asmore SQL Query commands are introduced. The next couple of examples will definitely be overwhelming to noviceSQL 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 queryscope 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 where we are actually going to tell SQL to create the new table, which isnamed orders .

Each table column has its own set of guidelines or schema, and the lines of code above contained in parenthesis() are telling SQL how to go about setting up each column schema. Table columns are presented in list format, andeach schema is separated with a comma (,). It isn't important to fully understand exactly what all of these schemadetails mean just yet. They will be explained in more detail throughout the remainder of the tutorial. For now, just takenote that we are creating a new, empty SQL table named orders , and this table is 5 columns wide.

sql - insert data into your new table

Next, we will use SQL's INSERT command to draw up a query that will insert a new data row into our brand newSQL table, orders . If you're already familiar with everything we've covered so far, please execute the query belowand then skip ahead and start learning about other SQL Queries. 

SQL Insert Query:

USE mydatabase;

Page 4: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 4/49

 INSERT INTO orders(customer,day_of_order,product, quantity)VALUES('Tizag','8/1/08','Pen',4);

SQL Insert Query Results:

(1 row(s) affected)

This message ("1 row(s) affected") indicates that our query has run successfully and also informs us that 1 rowhas been affected by the query. This is the desired result as our goal was to insert a single record into the newlyformedorders table.

Listed above is a typical INSERT query used to insert data into the table we had previously created. The first line("USE mydatabase;") identifies the query scope and the line after indicates what it is we'd like SQL to do for us.("INSERT INTO orders") inserts data into the orders table. Then, we have to list each table column by name(customer,day_of_order,product, quantity) and finally provide a list of values to insert into each table columnVALUES('Tizag','8/1/08','Pen',4).

You may notice that we have not included the id column, and this is intentional. We have set this column up in away that allows SQL to populate this field automatically, and therefore, we do not need to worry about including it inany of our INSERT statements. (More on this later.)

sql - queries

SQL coins the term query as the name for its commands. Basically, all SQL code is written in the form of a querystatement and then executed against a database. All SQL queries perform some type of data operation such asselecting data, inserting/updating data, or creating data objects such as SQL databases and SQL tables. Each querystatement 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 that willreturn 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 essentiallytell 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 covering in thenext lesson, SQL Select. 

SQL Query Examples:

-- Inserts data into a SQL Database/Table

Page 5: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 5/49

INSERT INTO orders (customer,day_of_order,product, quantity)VALUES('Tizag','8/1/08','Pen',4);

-- Selects data from a SQL Database/TableSELECT * FROM orders;

-- Updates data in a Database/TableUPDATE orders SET quantity = '6'

WHERE id = '1'

More information about these queries can be found at the following links: SQL Insert, SQL Update, SQL Delete 

sql - query structure review

Structurally, each SQL query we have seen in this lesson are similar. Each start with a clause telling SQL whichoperation to perform and the remaining lines provide more detailed information as to how we want SQL to go aboutperforming each SQL Command.

sql - selectSQL SELECT may be the most commonly used command by SQL programmers. It is used to extract data 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 want SQL togo and fetch. The second part of any SELECT command is the "FROM WHERE". It identifies where to fetch the data

from, which may be from a SQL table, a SQL view, or some other SQL data object.

Now we would like SQL to go and fetch some data for us from the orders table that was created in the previouslesson. 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, by following the schemaoutlined below.

SQL Select Query Code:

USE mydatabase;

SELECT id, customer, day_of_order, product, quantityFROM 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 ofthe SELECT statement.

Page 6: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 6/49

SQL Select Query: Rearranged:

USE mydatabase;

SELECT day_of_order, customer, product, quantityFROM orders;

SQL Orders Table Results:

day_of_order  customer  product quantity 

2008-08-01 00:00:00.000 Tizag Pen 4

By rearranging the table column list inside the SELECT statement, we altered the appearance of the result set.Also, by not including the id column in the list of table columns, SQL did not fetch any column data for this columnbecause we didn't ask SQL to do so.

sql - select all (*)

"SELECT (*)" is a shortcut that can be used to select all table columns rather than listing each of them by name.

Unfortunately, going this route doesn't allow for you to alter the presentation of the results.

SQL Select All Query:

USE mydatabase;

SELECT *FROM orders;

SQL Orders Table Results:

id customer day_of_order  product quantity 

1 Tizag 2008-08-01 00:00:00.000 Pen 4

sql - selecting data

The (*) query statement should be used with caution. Using this against our little tutorial database will surely dono harm, but using this query against an extremely large database may not be the best practice. Large databasesmay have web services or applications attached to them, so frequently updating and accessing large quantities datamay temporarily lock a table for fractions of a second or more. If this disruption happens to occur just as some pieceof data is being updated, you may experience data corruption.

Taking every precaution to avoid data corruption is in your best interest as a new SQL programmer. Corrupteddata may be lost and never recovered, and it can lead to even more corruption inside a database. The best habits areto be as precise as possible, and in the case of select statements, this often means selecting minimal amounts ofdata when possible.

At this point, you should feel comfortable with SELECT and how to look into your database and see actual datarows residing inside of tables. This knowledge will prove invaluable as your SQL skills develop beyond the basics andas you begin to tackle larger, more advanced SQL projects.

sql - where

The WHERE clause sets a conditional statement, and it can be used with any type of SQL query. As the selectquery executes, SQL processes one row at a time. Each time the conditional statement is met (returns true), a row

Page 7: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 7/49

is returned as a result. SQL WHERE is essentially, a filtering mechanism for SQL queries and is a tremendous assetto any aspiring SQL developer.

Advertise on Tizag.com 

SQL Where Query:

USE mydatabase;

SELECT *FROM ordersWHERE customer = 'Tizag'

As we take a look at the results, notice how only the rows that meet the criteria (where the customer columnvalue is Tizag ) are returned. In this example, we are using the WHERE clause to filter out rows and only selectingdata 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 2

Conditional statements are not unique to SQL, and neither are operators. Operators are symbols such as (=) or(<), and they are seen inside of conditional statements and expressions in SQL and other programming languages.While we're not going to dive into much detail about the different kinds of operators yet, it is a good idea to be familiarwith them and be able to recognize them inside of conditional statements as we look over the next few examples.

sql - where queries

With the WHERE clause on our tool belts, we can be more creative when querying for table rows. For instance,there may come a time where we would l ike to take a look at all the orders placed after a certain date.

SQL Where Date Query:

USE mydatabase;

SELECT *FROM orders

WHERE day_of_order > '7/31/08'

This conditional statement will return only the orders that have made it into the table since the end of July,

filtering out any orders in the table made prior to July 31

st

.

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

3 A+Maintenance 2008-08-16 00:00:00.000 Hanging Files 12

Page 8: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 8/49

4 Gerald Garner 2008-08-15 00:00:00.000 19" LCD Screen 3

Notice how the date value is formatted inside the conditional statement. We passed a value formattedMM/DD/YY, and we've completely neglected the hours, minutes, and seconds values, yet SQL is intelligent enough tounderstand this. Therefore, our query is successfully executed.

sql - where with multiple conditionals

A WHERE statement can accept multiple conditional statements. What this means is that we are able to selectrows meeting two different conditions at the same time.

Perhaps the easiest way to go about this is to add another condition to the previous example, where we retrievedonly the orders placed after July 31

st. We can take this example one step further and link two conditional statements

together with "AND".

SQL Where And:

USE mydatabase;

SELECT *FROM ordersWHERE day_of_order > '7/31/08'AND customer = 'Tizag'

At this point, we have sent SQL two conditional statements with a singleWHERE clause, essentially applying twofilters to the expected result set.

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

By applying the AND clause, SQL has now been asked to return only rows that meet both conditionalstatements. In this case, we would like to return all orders that were made before July 31

stand made by a specific

company - which is, in this case, Tizag . We have more examples of SQL AND/OR. Just follow the link.

sql - as

SQL AS temporarily assigns a table column a new name. This grants the SQL developer the ability to makeadjustments to the presentation of query results and allow the developer to label results more accurately withoutpermanently renaming table columns.

Advertise on Tizag.com SQL Select As Code:

USE mydatabase;

SELECT day_of_order AS "Date",customer As "Client",product,quantityFROM orders;

Page 9: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 9/49

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 - operatorsSQL 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 areused to compare one value against another. Each of these characters have special meaning, and when SQL comesacross them, they help tell SQL how to evaluate an expression or conditional statement. Most operators will appearinside of conditional statements in the WHERE clause of SQL Commands.

Advertise on Tizag.com 

Operators come in three flavors: mathematical, logical, and equality. Mathematical operators add, subtract,multiply, and divide numbers. Logical operators include AND and OR . Take note of the following tables for futurereference.

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

SQL Equality Operator Query:

USE mydatabase;

SELECT customer,day_of_orderFROM ordersWHERE 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 with a dategreater than '7/31/08' .

sql - equality operator table

Page 10: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 10/49

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

SQL Equality Operators:

Operator  Example Defined  Result 

=, IS 5 = 5 5 equal to 5? True

!=, IS NOT 7 != 2 7 IS NOT (!=) equal to 2? True

< 7 < 4 7 less than 4? False

> 7 > 4 greater than 4? True

<= 7 <= 11 Is 7 less than or equal to 11? True

>= 7 >= 11 Is 7 greater than or equal to 11? False

sql - mathematical operators

SQL mathematical operations are performed using mathematical operators (+, -, *, /, and %). We can use SQLlike a calculator to get a feel for how these operators work.

SQL Mathematical Operators:

SELECT15 + 4, --Addition15 - 4, --Subtraction15 * 4, --Multiplication15 / 5, -- Division15 % 4; --Modulus

SQL Results:

Addition Subtraction Multiplication Division  Modulus 

19 11 60 3 3

Modulus may be the only unfamiliar term on the chart. Modulus performs division, dividing the first digit by thesecond digit, but instead of returning a quotient, a "remainder " value is returned instead.

Modulus Example:

USE mydatabase;

SELECT (5 / 2) -- = 2.5SELECT (5 % 2) -- = 1 is the value that will be returned

sql - logical operators

These operators provide you with a way to specify exactly what you want SQL to go and fetch, and you may beas specific as you'd like! We'll discuss these a little later on and provide some real world scenarios as well.

We cover these operators thoroughly in the SQL AND/OR lesson.

  AND - Compares/Associates two values or expressions

  OR - Compares/Associates two values or expressions

Page 11: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 11/49

sql - create

SQL CREATE is the command used to create data objects, including everything from new databases and tablesto views and stored procedures. In this lesson, we will be taking a closer look at how table creation is executed inthe SQL world and offer some examples of the different types of data a SQL table can hold, such as dates, numbervalues, 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 each lineindividually.

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 mydatabase) andwe've seen it before so let's skip ahead to the next line, line 2 (CREATE TABLE inventory). This line informs SQL ofthe plan to create a new table using the CREATE clause and specifies the name of the new table (inventory). In thiscase, we plan on creating an inventory table to maintain a current inventory of store 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 hard as itseems. This is the first line that declares how to set up the first table column inside the new inventory 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 identitycolumn, the column essentially turns into an automated counter. As new rows are inserted into the table, this columnvalue will automatically increment (count up). The parameters (1,1) tell SQL which number to start counting from andby how many to increment each value. In this case, we'll start with 1, and increment by 1 each time a new row isinserted into our database. For example, the first INSERT command run against the inventory table will have an idvalue of 1, and each consecutive row inserted thereafter will increment by one (1, 2, 3, 4 ... etc). This identity tablecolumn is essentially counting each inserted row and also ensuring that we have a unique identifier value. This isimportant since this column has also been identified as a primary key (see below).

  PRIMARY KEY = This places a restraint on this column (no duplicate values)

Page 12: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 12/49

Bringing up the tail-end of Line 3 is reserved for specifying any unique attributes to associate with this tablecolumn. In this case, we have told SQL that this column will act as the PRIMARY KEY for the inventory table.Declaring this column as the PRIMARY KEY places a restraint on this column meaning no duplicate values may existin this column and SQL will throw an error message if an attempt is made to enter duplicate data. Since this row is setto automatically increment each time a new record is added, we know that this column will always be a unique value.

SQL Create Line 4:

product VARCHAR(50) UNIQUE,

Line 4 specifies the name and type of the second column in the inventory table. Product stands for the inventorytable product name and this column is set as a VARCHAR(50) , which means it will be able to handle numbers,letters, and special characters as values. In other words, "Any words, numbers, or special characters can be placedinto this column value, with a 50 character limit."

The UNIQUE attribute tells SQL that this table column must be a UNIQUE value at all times. This restraint willstop us from accidentally inserting duplicate records for the same product , which will serve as an aid to us to helpmaintain data integrity.

SQL Create Line 5,6:quantity INT,price DECIMAL(18,2)

Now that you are more familiar with the structure of this query, lines 5 and 6 should look less like a foreignlanguage and more like SQL code. These lines are creating two more table columns: quantity and price . Since theprice column will be dealing with decimals, we have set this column to a DECIMAL data type to handle decimals(sometimes called floating point numbers).

And there you have it, here's another look at the query:

SQL Create Table Query:

USE mydatabase;

CREATE TABLE inventory(

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

);

This SQL command will create a new, empty table called inventory , where we will begin to capture storeinventory data to keep track of the price and current stock of items for our make believe online store.

At this point, this table has been created but remains empty, containing no data. Let's go ahead and add somerecords into this table so that we can then use this table to further our learning of SQL. Since we are now alreadyfamiliar with theINSERT command, we can run the following commands all at once, so feel free to copy and pastethis code into the query window and execute.

SQL Insert Into:

USE mydatabase;

INSERT INTO inventory

VALUES('19" LCD Screen','25','179.99');

Page 13: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 13/49

INSERT INTO inventoryVALUES('HP Printer','9','89.99');INSERT INTO inventoryVALUES('Pen','78','0.99');INSERT INTO inventoryVALUES('Stapler','3','7.99');INSERT INTO inventoryVALUES('Hanging Files','33','14.99');

INSERT INTO inventoryVALUES('Laptop','16','499.99');

Successful execution of the above query should yield messages indicating that the queries have runsuccessfully.

SQL Results:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

We can double-check the results by running a SELECT (*) query and doing so will retrieve all records SQL hasstored inside the inventory table.

SQL Code:

USE mydatabase;

SELECT *FROM inventory;

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

5 Hanging Files 33 14.99

6 Laptop 16 499.99

In creating this new table with data that relates to data inside the orders table, you have unknowingly createda relational database. We can now take a list of items ordered by our customers and verify that these items are instock as purchases continue to flow in, so long as we maintain an up-to-date inventory table.

This is terrific news as you are now well on your way to take your SQL programming skills to the next level!

Page 14: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 14/49

sql - insert

To use the INSERT command, we must first have an understanding of where we would like to insert data andwhat types of data we want to insert. Do we plan on inserting numbers? Strings? Files? Let's return tothe 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 insert newdata (a new row) into a table by specifying a list of values to be inserted into each table column. The arrangement ofvalues is important, and how they are arranged in the code corresponds to how the data values will be arranged inthe 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 to hold.The quantity column, for example, is expecting a number or integer of some sort and the day_of_order column isexpecting 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 that whenwe created the orders table, we gave the id column a unique attribute called identity. SQL handles identity columnsautomatically for us and therefore, we do not need to manually insert data into this column.

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

Now when we run the SELECT (*) query, SQL should return two rows with our statement instead of only a singlerow.

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 Pen 4

Page 15: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 15/49

2 Tizag 2008-08-01 00:00:00.000 Stapler 1

sql - inserting values

As a shortcut, you may omit the table columns entirely and only supply thevalues in the INSERT statement:

SQL Insert Shortcut:

USE mydatabase;

INSERT INTO ordersVALUES('A+Maintenance','8/16/08','Hanging Files',12);

Again, we can skip the id column because SQL is able to identify that this column is an identity column andhandle it accordingly.

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

3 A+Maintenance 2008-08-16 00:00:00.000 Hanging Files 12

Before moving on, let's add some more rows and execute some more INSERT queries. If you are using SQLExpress, you should be able to copy the entire code section below and execute all the queries at once and then trackthe results with the verification query (SELECT * FROM orders).

SQL Inserts:

USE myDatabase;

INSERT INTO ordersVALUES('Gerald Garner','8/15/08','19" LCD Screen',3)INSERT INTO ordersVALUES('Tizag','7/25/08','19" LCD Screen',3);INSERT INTO ordersVALUES('Tizag','7/25/08','HP Printer',2);

Final 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

3 A+Maintenance 2008-08-16 00:00:00.000 Hanging Files 124 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 - and

Page 16: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 16/49

SQL AND links together two or more conditional statements for increased filtering when running SQLcommands. AND helps the developer query for very specific records while answering questions like, "I want to viewall orders made by a certain customer AND made on a special date." There is no limit to the numberof AND/OR conditions that can be applied to a query utilizing the WHERE clause. This makes it possible for thedeveloper to be as precise as needed when querying for results.

Advertise on Tizag.com 

SQL And Code:USE mydatabase;

SELECT *FROM ordersWHERE 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 singlecondition with multiple circumstances (filters). Each filter removes rows from the result set that doesn't meet thecondition.

sql - or

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

SQL Or Code:

USE mydatabase;

SELECT *FROM ordersWHERE product = 'Pen'OR product = '19" LCD Screen';

SQL Results:

id customer  day_of_order  product  quantity 

1 Tizag 2008-08-01 00:00:00.000 Pen 4

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

The first record returned matches the first condition since the product = 'Pen'. The two records after that matchthe other condition; the product in each of those orders is the '19" LCD Screen'. This type of logic allows thedeveloper to filter results based on one or more conditions.

SQL AND allows the developer to query for more specific data by linking together conditional statements. On theother end of the spectrum, SQL OR creates a new, independent condition not linked to any other conditionalstatement.

Page 17: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 17/49

sql - and / or combination

Conditional statements can be grouped together using parentheses (). Doing so links together conditions andprovides robust solutions for data querying.

SQL And/Or Code:

USE mydatabase;

SELECT *FROM ordersWHERE (quantity > 2 AND customer = 'Tizag')OR (quantity > 0 AND customer = 'Gerald Garner')

By encapsulating the first two conditions (quantity > 2 AND customer = 'Tizag') SQL now treats this as a singlecondition, and the same is true for the next line. These two conditions have been linked together withthe OR operator, creating very unique behavior.

SQL is now looking for rows where the customer is Tizag AND the quantity is more than 2 , and ALSO looking for

rows where the customer is Gerald Garner AND the quantity is greater than 0 . All rows meeting either condition will bereturned as demonstrated in our results below.

SQL Results:

id customer  day_of_order  product  quantity 

1 Tizag 2008-08-01 00:00:00.000 Pen 4

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

sql - between

BETWEEN is a conditional statement found in the WHERE clause. It is used to query for table rows that meet acondition falling between a specified range of numeric values. It would be used to answer questions like, "How manyorders did we receive BETWEEN July 20

thand August 5

th?"

Advertise on Tizag.com 

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

Page 18: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 18/49

BETWEEN essentially combines two conditional statements into one and simplifies the querying process for you.To understand exactly what we mean, we could create another query without using the BETWEEN condition and stillcome up with the same results, (using AND instead).

SQL Select Between:

USE mydatabase;

SELECT *FROM ordersWHERE day_of_order >= '7/20/08'AND day_of_order <= '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

As you can see from comparing the results of these two queries, we are able to retrieve the same data, but youmay find BETWEEN easier to use and less cumbersome than writing two different conditional statements. In the end,the preference is really up to the individual writing the SQL Code.

sql - order by

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

Advertise on Tizag.com SQL Order by query:

USE mydatabase;

SELECT *FROM ordersWHERE 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 has nowbeen sorted (low to high) according to the date value. In other words, the oldest order to the newest 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

Page 19: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 19/49

sql - ascending descending

The default sort order for ORDER BY is an ascending list, [a - z] for characters or [0 - 9] for numbers. As analternative to the default sorting for our results, which is ASCENDING (ASC), we can instead tell SQL to order thetable columns in a DESCENDING (DESC) fashion [z-a].

SQL Order by Descending:

USE mydatabase;

SELECT *FROM ordersWHERE customer = 'Tizag'ORDER BY day_of_order DESC

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 15 Tizag 2008-07-25 00:00:00.000 19" LCD Screen 3

6 Tizag 2008-07-25 00:00:00.000 HP Printer 2

If you compare these results to the results above, you should notice that we've pulled the same information but itis now arranged in a reverse (descending) order.

sql - sorting on multiple columns

Results may be sorted on more than one column by listing multiple column names in the ORDER BY clause,similar to how we would list column names in each SELECT statement.

SQL Order by Multiple columns:

USE mydatabase;

SELECT *FROM ordersORDER BY customer, day_of_order;

This query should alphabetize by customer, grouping together orders made by the same customer and then bythe purchase date. SQL sorts according to how the column names are listed in the ORDER BY clause.

SQL Results:

id customer  day_of_order  product  quantity 

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

Page 20: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 20/49

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 verypowerful command in the SQL world. It has the ability to update every single row in a database with the execution ofonly a single query. Due to UPDATE's supreme authority, it is in your best interest to always includea WHERE clause when working with UPDATE query statements. That way, you will not accidentally update morerows than you intend to.

Advertise on Tizag.com 

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

SQL Update Query:

USE mydatabase;

UPDATE ordersSET 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 6

The orders table now indicates that the customer Tizag will be ordering 6 Pens instead of 4 . If

the WHERE condition is removed from this statement, SQL would modify every row with the new quantity valueof 6 instead of just the single row that meets the condition of id = "1" . SQL UPDATE replaces data, much likeoverwriting a previously saved file on a computer hard drive. Once you click "Save," the old file is lost and replacedwith the new file. Once an UPDATE command has been executed, the old data values are lost, being overwritten bythe new value.

sql - update incrementing a value

Page 21: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 21/49

In the previous example, an order quantity was updated from 4 to 6 . Say what we really wanted to do was notnecessarily change it to 6 , but to add 2 to the original order quantity. Updating the order quantity from 4 to 6 mighthave gotten the job done in that scenario, but that solution doesn't scale well. In the long run, we wouldn't get verymuch "bang for our buck," as they say.

So, perhaps a better way to tackle the same problem would be to increment the existing value (add 2) rather thanupdating with a single, static value. So, instead of setting the quantity table column to a specific value of 6 , we can

send it the current table column value directly and then add 2 to that already existing value.

SQL Update Code:

USE mydatabase;

UPDATE ordersSET quantity = (quantity + 2)WHERE id = '1'

SQL Results:

id customer day_of_order  product quantity 

1 Tizag 2008-08-01 00:00:00.000 Pen 8

Executing this update statement instead of the first update query is a huge timesaver. We no longer need toknow the quantity of the order beforehand and we can add or subtract values from it in its current state. All we needto know is that we need to add 2 more to the quantity column to update the order correctly. This query is also morescalable, meaning we can update many rows at once. We will do so in the next example.

sql - update multiple rows

As mentioned earlier, removing the WHERE clause from any UPDATE command is generally not a good ideasince doing so will result in SQL updatingevery row in the table. However, since the intention of this next example isto update multiple rows, let's go ahead and remove the WHERE clause from the above example.

SQL Update Multiple Rows:

USE mydatabase;

UPDATE ordersSET quantity = (quantity + 2)

SQL Results:

(6 row(s) affected)

SQL Results:

id customer  day_of_order  product  quantity 

1 Tizag 2008-08-01 00:00:00.000 Pen 10

2 Tizag 2008-08-01 00:00:00.000 Stapler 3

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

5 Tizag 2008-07-25 00:00:00.000 19" LCD Screen 5

6 Tizag 2008-07-25 00:00:00.000 HP Printer 4

Page 22: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 22/49

sql update multiple values

SQL UPDATE can also be utilized to change multiple column values at once. Once again, let's update the sameorder id (1) changing the quantity of products ordered. But let's also take it another step further, by changing thequantity only when the products are Hanging Files .

SQL Update Multiple Values:

USE mydatabase;

UPDATE ordersSET quantity = '11',Product = 'Hanging Files'WHERE id = '1'

SQL Results:

id customer day_of_order  product  quantity 

1 Tizag 2008-08-01 00:00:00.000 Hanging Files 11

The results show that we have successfully updated an order (order id 1). Notice that after the SET keyword, thecolumn and value sets are listed with each column/value pair being separated with a comma (,).

sql - alter

SQL ALTER is the command used to add, edit, and modify data objects like tables, databases, andviews. ALTER is the command responsible for making table column adjustments or renaming table columns. Newtable 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 NULL5 Tizag 2008-07-25 00:00:00.000 19" LCD Screen 5 NULL

6 Tizag 2008-07-25 00:00:00.000 HP Printer 4 NULL

As you can see from the results panel, SQL has added an additional column, discount, to the orders table. Sincethis column was just created, it contains no data, and only NULL values have been returned.

Page 23: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 23/49

sql - alter table: modify column

SQL table columns can be altered and changed using the MODIFY COLUMN command. This allows thedeveloper the opportunity to mold table columns or adjust settings as needed.

SQL Modify Column:

USE mydatabase;

ALTER TABLE ordersALTER COLUMN discount DECIMAL(18,2);

Above, we have modified the new discount table column changing the column data type from a varchar toa decimal table column. This example can be expanded to modify table columns as needed by the developer.

sql - sql alter table: drop

This column can be deleted using the SQL DROP command. Once this column has been dropped, however, the

data stored inside of it will be lost forever. Proceed with caution!

SQL Drop Column Code:

USE mydatabase;

ALTER TABLE ordersDROP COLUMN discount;

sql - distinct

SQL SELECT DISTINCT is a very useful way to eliminate retrieving duplicate data reserved for very specificsituations. To understand when to use theDISTINCT command, let's look at a real world example 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 thatrepresents different orders made by some of our very loyal customers over a given time period. Let's pretend that wehave just heard word from our preferred shipping agent that orders made in August require no shipping charges, andwe now have to notify our customers. We do not want to send mailers to all of our customers, just the ones that haveplaced orders in August. Also, we want to avoid retrieving duplicate customers as our customers may have placedmore 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 customerFROM ordersWHERE day_of_order BETWEEN '7/31/08' AND '9/1/08';

SQL Results:

Page 24: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 24/49

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 the good news withoutworrying about contacting the same customer multiple times.

sql - subqueries

Subqueries are query statements tucked inside of query statements. Like the order of operations from your highschool Algebra class, order of operations also come into play when you start to embed SQL commands inside ofother SQL commands (subqueries). Let's take a look at a real world example involving theorders table and figure outhow 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 wraps around atable column and quickly returns the current highest (max) value for the specified column. We are going to use thisfunction 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 littledilemma.

SQL Select Subquery Code:

USE mydatabase;

SELECT *FROM ordersWHERE 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 14

This query is a dynamic query as it pulls current information and will change if a new order is placed. Utilizing asubquery we were able to build a dynamic and robust solution for providing us with current order information.

Page 25: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 25/49

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 waychange the data or table structure. JOIN is another way to select specific data from two or 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 columnwe want to join on and a condition to meet for the JOIN to happen. This should sound a little confusing as there ismuch going on in a JOIN query, so let's take a look at an example:

SQL Join Query Code:

USE mydatabase;

SELECT *FROM ordersJOIN inventoryON orders.product = inventory.product;

SQL Join Results:

id customer  day_of_order  product  quantity  id product  quantity price 

1 Tizag2008-08-01

00:00:00.000

Hanging

Files11 5

Hanging

Files33 14.99

2 Tizag2008-08-01

00:00:00.000Stapler 3 4 Stapler 3 7.99

3 A+Maintenance2008-08-16

00:00:00.000

Hanging

Files14 5

Hanging

Files33 14.99

4 Gerald Garner2008-08-1500:00:00.000

19" LCDScreen 5 1

19" LCDScreen 25 179.99

5 Tizag2008-07-2500:00:00.000

19" LCDScreen

5 119" LCDScreen

25 179.99

6 Tizag2008-07-2500:00:00.000

HP Printer 4 2 HP Printer 9 89.99

The line beginning with JOIN (Line 4) is where we tell SQL which table we would like to join. The next line (Line5) is a different story. Here is where we have specified the condition to JOIN ON . In this case, both tables haveidentical product columns which makes them an ideal target for a join. Basically we are temporarily merging thetables 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 thatmatch to merge the tables together. In our make-believe store world, this let's us join the inventory table withthe 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 andunderstand. We will replace the (*) parameter with a list containing only the table columns we are interested inviewing.

SQL Join:

Page 26: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 26/49

USE mydatabase;

SELECT orders.customer,orders.day_of_order,orders.product,orders.quantity as number_ordered,inventory.quantity as number_instock,inventory.price

FROM ordersJOIN inventoryON orders.product = inventory.product

SQL Results:

customer  day_of_order  product  number_ordered number_instock price 

Tizag2008-08-01

00:00:00.000

Hanging

Files11 33 14.99

Tizag2008-08-0100:00:00.000

Stapler 3 3 7.99

A+Maintenance 2008-08-1600:00:00.000

HangingFiles

14 33 14.99

Gerald Garner2008-08-15

00:00:00.000

19" LCD

Screen5 25 179.99

Tizag2008-07-25

00:00:00.000

19" LCD

Screen5 25 179.99

Tizag2008-07-25

00:00:00.000HP Printer 4 9 89.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 readnow 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 ofreturning 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 ordersRIGHT JOIN inventoryON orders.product = inventory.product

SQL Results:

id  customer  day_of_order  product  quantity  id product  quantity price 

4 Gerald Garner 2008-08-15 19" LCD 5 1 19" LCD 25 179.99

Page 27: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 27/49

00:00:00.000 Screen Screen

5 Tizag2008-07-25

00:00:00.000

19" LCD

Screen5 1

19" LCD

Screen25 179.99

6 Tizag2008-07-25

00:00:00.000HP Printer 4 2 HP Printer 9 89.99

NULL NULL NULL NULL NULL 3 Pen 78 0.99

2 Tizag2008-08-01

00:00:00.000Stapler 3 4 Stapler 3 7.99

1 Tizag2008-08-01

00:00:00.000

Hanging

Files11 5

Hanging

Files33 14.99

3 A+Maintenance2008-08-16

00:00:00.000

Hanging

Files14 5

Hanging

Files33 14.99

NULL NULL NULL NULL NULL 6 Laptop 16 499.99

You should see a new row at the bottom of the results box with a bunch of NULL values. This is a result ofthe RIGHT JOIN and is the intended result from running the query. We end up with an extra row because inside ofthe inventory table, the Laptop item was not joined with a product from the orders table. This just means that we havenot sold a laptop as of yet and it shouldn't be much a surprise since we already know from querying the orders tablein 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 theconditional statement. All records that exist in the table on the right side of the conditional statement (ONorders.product = inventory.product) will be returned and NULL values will be placed on the left if no matches arefound.

sql - left join

SQL LEFT JOIN works exactly the same way as RIGHT JOIN except that they are opposites.NULL values willappear on the right instead of the left and all rows from the table on the left hand side of the conditional will bereturned.

Unfortunately, we will not be able to show a very intuitive example of a LEFT JOIN because of how our tablesare structured. The orders table should always have a matching inventory item and if not, that means we are in bigtrouble as we could be selling items we do not carry in inventory. For good measure, here's what a LEFT JOIN wouldlook like:

SQL Left Join:

USE mydatabase;

SELECT *

FROM ordersLEFT 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 amore detailed picture of what the data represents. By merging these two data sets, we were able to peer into ourdatabase and ensure that each item ordered so far is in stock and ready to be shipped to our customers.

Page 28: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 28/49

sql - in

SQL IN is an operator used to pull data matching a list of values. A scenario where this proves useful would be ifwe wanted to retrieve customer data for two or more customers. We can use the IN operator to specify a list ofcustomer 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 and slightlyalters the meaning as well. Instead of listing a single value, you may list multiple values and SQL will retrieve theresults for each value listed.

SQL In:

USE mydatabase;

SELECT *FROM ordersWHERE 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 insidethe IN clause ('Gerald Garner','A+Maintenance'). This is a great way to query for all orders made by a handful ofdifferent 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. Runningany 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 productFROM ordersWHERE 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 thisquery to a subquery and use this query as an input list to check the inventory table to see if we have any of theseitems in stock.

Page 29: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 29/49

SQL In:

USE mydatabase;

SELECT *FROM inventoryWHERE product in

(SELECT product

FROM ordersWHERE customer IN ('Gerald Garner','A+Maintenance'));

SQL Results:

id product  inventory price 

1 19" LCD Screen 25 179.99

5 Hanging Files 33 14.99

By specifying a sub query as our list of values we were able to take advantage of the relationship our tables havewith each other and create a very dynamic query. This query saves us the time of scrolling through the entireinventory 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 resultset.

SQL Not In:

USE mydatabase;

SELECT *FROM inventoryWHERE product NOT IN

(SELECT product

FROM ordersWHERE customer IN ('Gerald Garner','A+Maintenance'));

SQL Results:

id product  quantity price 

2 HP Printer 9 89.99

3 Pen 78 0.99

4 Stapler 3 7.99

6 Laptop 16 499.99

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

Advertise on Tizag.com 

Page 30: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 30/49

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

SQL Select Case Code:

USE mydatabase;

SELECT product,'Status' = CASEWHEN 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 without actuallyaltering any data. This would be a great way to implement some feature in an online catalog to allow users to checkthe 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 perfectopportunity to write a CASE query and alter the inventory sale prices at the presentation level rather than actuallychanging the price inside of the inventory table. CASE provides a way for the store owner to mask the data but stillpresent 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 theresults contain both the quantity of items purchased and the price from the inventory table. To accomplish this we willneed 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 ordersJOIN inventoryON orders.product = inventory.product

Page 31: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 31/49

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:

id customer  quantity product  price 

1 Tizag 11 Hanging Files 14.99

2 Tizag 3 Stapler 7.99

3 A+Maintenance 14 Hanging Files 14.99

4 Gerald Garner 5 19" LCD Screen 179.99

5 Tizag 5 19" LCD Screen 179.99

6 Tizag 4 HP Printer 89.99

Next we need to look at reducing the prices of the items according to our sale price. For the purpose of thisexercise, 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' = CASEWHEN price > 0 THEN (price * .75)

ENDFROM ordersJOIN inventoryON orders.product = inventory.product

Multiplying the current price by .75 reduces the price by approximately 25%

, successfully applying the changeswe would like to see but doing so without actually changing any data.

SQL Results:

id customer  quantity product  price  SALE_PRICE 

1 Tizag 11 Hanging Files 14.99 11.2425

2 Tizag 3 Stapler 7.99 5.9925

3 A+Maintenance 14 Hanging Files 14.99 11.2425

4 Gerald Garner 5 19" LCD Screen 179.99 134.99255 Tizag 5 19" LCD Screen 179.99 134.9925

6 Tizag 4 HP Printer 89.99 67.4925

The results speak for themselves as the records returned indicate a new table column with the calculated salesprice now listed at the end of each row.

Page 32: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 32/49

Since SQL CASE offers a conditional statement (price > 0), it wouldn't take much more effort to create someconditional statements based on how many products each customer had ordered and offer different discounts basedon the volume of a customer order.

For instance, as a web-company, maybe we would l ike to offer an additional 10%

discount to orders totaling morethan

$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' = CASEWHEN (orders.quantity * price) > 100 THEN (price * .65)ELSE (price * .75)

ENDFROM ordersJOIN inventoryON orders.product = inventory.product

:

id customer  quantity product  price  SALE_PRICE 

1 Tizag 11 Hanging Files 14.99 9.7435

2 Tizag 3 Stapler 7.99 5.9925

3 A+Maintenance 14 Hanging Files 14.99 9.7435

4 Gerald Garner 5 19" LCD Screen 116.9935 134.9925

5 Tizag 5 19" LCD Screen 179.99 116.9935

6 Tizag 4 HP Printer 89.99 58.4935

With this query, we have now successfully reduced all orders by 25%

and also applied an additional 10%

discountto any order totaling over

$100.00.

In each of the examples above, SQL CASE has been utilized to perform presentation level adjustments on datavalues and its versatility provides limitless results.

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 customerFROM ordersGROUP BY customer;

Page 33: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 33/49

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 actuallyduplicated the behavior of SELECT DISTINCT , but you have also seen firsthand how GROUP BY accepts a tablecolumn 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 byeach of our customers.

SQL Code:

USE mydatabase;

SELECT customer, SUM(quantity) AS "Total Items"FROM ordersGROUP BY customer;

SQL Results:

customer  Total Items 

A+Maintenance 14

Gerald Garner 5

Tizag 23

With the addition of the aggregate SUM() function, we've let SQL calculate how many products have beenordered 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 ofa single query statement.

SQL Code:

USE mydatabase;

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

SQL Results:

product  Total Items 

19" LCD Screen 10

Hanging Files 25

HP Printer 4

Stapler 3

Page 34: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 34/49

GROUP BY would also be a great way to calculate how much total cash of our customers has spent. Let's take alook at what that query may look like.

SQL Code:

USE mydatabase;

SELECT customer,SUM((orders.quantity * inventory.price)) AS "COST"

FROM ordersJOIN inventoryON orders.product = inventory.productGROUP BY customer;

SQL Results:

product  COST 

A+Maintenance 209.86

Gerals Garner 899.95

Tizag 1448.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 ordersGROUP BY day_of_order,productORDER BY day_of_order;

SQL Results:

day_of_order  product  Total 

2008-07-25 00:00:00.000 19" LCD Screen 5

2008-07-25 00:00:00.000 HP Printer 4

2008-08-01 00:00:00.000 Hanging Files 11

2008-08-01 00:00:00.000 Stapler 3

2008-08-15 00:00:00.000 19" LCD Screen 5

2008-08-16 00:00:00.000 Hanging Files 14

This query will group together and sum the total number of products purchased on any given date, regardless ofwhat customer has purchased the item. It's a very useful query to keep in mind.

sql - having

Page 35: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 35/49

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 mustalso appear in the GROUP BY clause.

SQL Having:

USE mydatabase;

SELECT day_of_order,product,SUM(quantity) as "Total"

FROM ordersGROUP BY day_of_order,product,quantityHAVING quantity > 7ORDER BY day_of_order;

SQL Results:

day_of_order  product  Total 

2008-08-01 00:00:00.000 Hanging Files 11

2008-08-16 00:00:00.000 Hanging Files 14

The quantity column is now considered aggregated in SQL terms, because its values have been summedtogether 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 - views

SQL VIEWS are data objects, and like SQL Tables, they can be queried, updated, and dropped. A SQL VIEW isa virtual table containing columns and rows except that the data contained inside a view is generated dynamicallyfrom SQL tables and does not physically exist inside the view itself.

Advertise on Tizag.com 

SQL Create View Code:

CREATE VIEW virtualInventoryASSELECT * 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. Viewscan 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

Page 36: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 36/49

2 HP Printer 9 89.99

3 Pen 78 0.99

4 Stapler 3 7.99

5 Hanging Files 33 14.99

6 Laptop 16 499.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), thesechanges will be reflected in the SQL VIEW automatically.

SQL Code:

USE mydatabase;

UPDATE inventorySET price = '1.29'WHERE product = 'Pen';

Execute the following query to verify the results:

SQL Verification Query Code:

USE mydatabase;

SELECT *FROM virtualInventoryWHERE product = 'Pen';

SQL Results:

id product  quantity price 

3 Pen 78 1.29

sql - drop view

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

SQL Drop View:

USE mydatabase;

DROP VIEW virtualInventory;

sql - dates

Date values are stored in date table columns in the form of a timestamp. A SQL timestamp is a recordcontaining date/time data, such as the month, day, year, hour, and minutes/seconds. It's not much different from thestandard date format.

Advertise on Tizag.com 

Date Columns:

Page 37: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 37/49

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() thatreturns 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 querystatements. 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 formattingrequirements.

SQL Code:

USE mydatabase;

SELECTISDATE('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 dateformats 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";

Page 38: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 38/49

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 datecalculations and work more in-depth with SQL Dates.

sql - datepart

DATEPART() is a SQL function used to extract all kinds of date information from timestamps, and it is a functionthat 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 of datedata 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 Example 

year yy, yyyy DATEPART(yy, getdate())

quarter qq, q DATEPART(qq, getdate())

Page 39: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 39/49

month mm, m DATEPART(mm, getdate())

dayofyear dy, y DATEPART(dy, getdate())

day dd, d DATEPART(dd, getdate())

week wk, ww DATEPART(wk, getdate())

weekday dw DATEPART(dw, getdate())

hour hh DATEPART(hh, getdate())

minute mi DATEPART(mi, getdate())

second ss DATEPART(ss, getdate())

millisecond ms DATEPART(ms, getdate())

sql - dateadd()

DATEADD() is the SQL function used to add and increment date values. Hours, minutes, months, and days canbe added to any date value. In fact, dates can be added based on any type of date part discussed in the 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 'year' datepart. By replacing the middle parameter with a negative value, we can utilize the same DATEADD() function tosubtract 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 thecalculation, a timestamp value returned. Also note that the date parameter can be based on another SQL function orthe result of a subquery.

SQL Code:

USE mydatabase;

Page 40: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 40/49

 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 theorders table, and we've been able to subtract one day from that value. While this information does not directly proveuseful, if we take this query one step further and place this statement in a WHERE as a subquery, we should be moresatisfied with the results.

SQL Code:

USE mydatabase;

SELECT *FROM ordersWHERE day_of_order >

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

SQL Results:

id customer  day_of_order  product  quantity 

1 Tizag 2008-08-01 00:00:00.000 Hanging Files 11

2 Tizag 2008-08-01 00:00:00.000 Stapler 3

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

5 Tizag 2008-07-25 00:00:00.000 19" LCD Screen 5

6 Tizag 2008-07-25 00:00:00.000 HP Printer 4

By placing this calculated date in the WHERE clause, we were able to pull all the records that have happenedwithin 30 days of the most recent order (2008-07-17 00:00:00.000). We are able to query the orders table andrequest this information with a dynamic query that will yield different results as new orders are placed and time goesby.

sql - delete command(s)

In the SQL world, databases, rows, and columns all have one thing in common: once a DELETE statement hasbeen executed successfully against them, the data they once contained is lost forever! Be very careful with thesecommands and be sure to properly backup all data before proceeding with any type of DELETE 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.

Page 41: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 41/49

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 usea WHERE condition when running any delete query or else you risk deleting too much data.

SQL Delete Query:

USE mydatabase;

DELETEFROM ordersWHERE customer = 'A+Maintenance';

SQL Results:

1 Row(s) affected

sql - truncateSQL 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 tablecolumn 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 beperformed on SQL objects including databases, tables, table columns, and SQL views. Dropping any of these objectsremoves them completely from your SQL application and all data contained in any of the data objects dropped arelost forever.

SQL Drop Examples:

USE mydatabase;

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

-- FOR USE WITH ALTER COMMANDSDROP COLUMN column_nameDROP FOREIGN KEY (foreign_key_name)

Page 42: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 42/49

The above example also includes the syntax to drop table columns and foreign keys. These items are outlined inthe SQL ALTER lesson.

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

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 the resultset 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 uniquerows of data. We challenge you to do this by reviewing the SQL Create queries and modifying them to create twobrand new employee tables.

SQL Select Union Code:

USE mydatabase;

SELECT * FROM employeesUNIONSELECT * 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 of every employee from the two tables, perhaps representing a list of employeesfrom two different departments.

The next example shows a more practical means of using a union clause. Here we will select all of ouremployees from both tables and join them with our invoices table to generate a complete list of sales from both storeson a given day.

SQL Code:

SELECT employees.Lastname, employees.Firstname, invoices.Sale, invoices.PriceFROM employees

INNER JOIN invoices

Page 43: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 43/49

ON employees.id = invoices.EmployeeIDUNIONSELECT employees2.Lastname, employees2.Firstname, invoices.Sale, invoices.PriceFROM employees2INNER JOIN invoicesON 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 - union all

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

SQL Code:

SELECT * FROM employeesUNION ALLSELECT * 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.PriceFROM employees

Page 44: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 44/49

INNER JOIN invoicesON employees.id = invoices.EmployeeIDUNION ALLSELECT employees2.Lastname, employees2.Firstname, invoices.Sale, invoices.PriceFROM employees2INNER JOIN invoicesON 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 - syntax - (speaking sql)

Syntax, by definition, means the study of linguistic rules and patterns. Every programming language, includingSQL, must follow a unique set of guidelines termed syntax. Punctuation, spaces, mathematical operators, and specialcharacters have special meaning when used inside of SQL commands and query statements. For example, each andevery 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. Syntaxerrors 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 inthis 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 executedafter 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 thiscommand 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 syntaxcode 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.

Page 45: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 45/49

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

Sample SQL Command:

USE

mydatabase;

The example above, though it does look different due to the capitalization and spacing, will yield the same resultsas 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. Cleancode allows another SQL developer to step right in where you have left off without missing a beat. A developer withdiligent coding habits will prevent many syntax errors before executing his/her scripts and also will be able to detectpossibly 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 indoing so and always do your best to follow good coding habits.

sql - data types

SQL data takes shape in several different forms, including character strings, numbers, file stores, and dates. SQLdevelopers call the shots as to what types of data will be stored inside each and every table column when creating aSQL 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 that will bestored inside the column. In other words, a SQL data type is a label and a guideline for SQL to understand what typeof 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)

Page 46: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 46/49

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

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

For the most part, date values are treated like numbers and they can even be added together and subtractedoffering 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 informationfrom 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 uniquesymbols. Set the table column type to VARCHAR or Text in order to incorporate string data types into SQL tables.

SQL Server Table Column Types:

bigint Integer value (-9,223,372,036,854,775,808 -9,223,372,036,854,775,807)

2^63

int  smaller Integer value (-2,147,483,648) - (2,147,483,647) 2^31

smallint  smaller Integer value (-32,768) - (32,767) 2^15

tinyint  smaller Integer values 0 - 255 2^8

bit  Integer data value (either 1 or 0 value) 1 or 0

decimal  Decimal values from -10^38 - 10^38 10^38

numeric  Decimal values from -10^38 - 10^38 10^38

money Money values (-922,337,203,685,477.5808) -

(922,337,203,685,477.5807) 2^63

smallmoney  Smaller Money Values (-214,748.3648) - (214,748.3647) 2^31

datetime  Date value (January 1, 1753) - (December 31, 9999)

smalldatetime  Smaller Date Value (January 1, 1900) - (June 6, 2079)

timestamp  Unique Number Value (updates when row is updated)

char  Character String Value (max 8,000 characters)

Page 47: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 47/49

varchar Character String Value maximum of 8,000 characters, unless otherwise

noted)

nchar  Character String Value (max 4,000 characters)

nvarchar  Character String Value (max 4,000 characters)

text  Character String Value (max 2,147,483,647 characters) 2^31ntext  Character String Value (max 1,073,741,823 characters) 2^30

binary  Binary Value (max 8,000 bytes)

varbinary  Binary Value (max 8,000 bytes)

image  Binary Value (max 2,147,483,647 bytes) 2^31

uniqueidentifier Global 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 SQLdeveloper runs across a NULL value in a database, it is generally an indication that this value is either new or has notbeen 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 mayspecify a custom default value instead of the NULL (nothing) value. Primary Key table columns do not allow NULLvalues since this column's sole purpose is to be the unique identifier for a table column. Having a NULL uniqueidentifier 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 mostprogramming languages including SQL and can provide the developer a means to 'test' and see if data exists or hasbeen modified. As a new programmer you may not fully understand the benefits a NULL value can bring, but withexperience, you will learn to hate/appreciate them.

sql - expressions

SQL Expressions are the pieces of a SQL query that compare values against other values or perform arithmeticcalculations. 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.

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 

Page 48: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 48/49

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:

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 SQLapplication. SQL also offers several built-in functions to perform what is known as aggregate data calculationsagainst 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;

Page 49: SQL- lokesh verma

8/3/2019 SQL- lokesh verma

http://slidepdf.com/reader/full/sql-lokesh-verma 49/49

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();