SQL Queries
SQL Queries
SQL
SQL may frequently pronounced “sequel” but the alternate pronunciation “S.Q.L.” is
also used. As the name implies, SQL is a computer language that you use to interact
with a database. In fact, SQL works with a specific type of database, called a
relational database.
SQL is more than a query tool, although that was its original purpose, and retrieving
data is still one of its most important functions. SQL is used to control all of the
functions of DBMS which provides for its users, including:
Data Definition Language. In DDL user define the structure and
organization of the stored data and relationships among the stored data
items.
SQL Queries
Query is a loose term that refers to a widely available set of SQL commands called
clauses. Each clause or command performs some sort of function against the
database. For instance, the create clause creates tables in databse and the select
clause selects rows that have been inserted into your tables.
Construction of Query begins with one of the following clauses:
Add
Drop
Create
Insert
Select
Update
Replace
Delete
SQL Code:
Select Command
Select command is use to select data from the tables located in a database.If we
need to SELECT information FROM a table.
To illustrate the above example, assume that we have the following table Name
"Store_Information" :
store_name Sales Date
Los Angeles $1500 Jan-05-2005
San Diego $250 Jan-07-2005
Los Angeles $300 Jan-08-2005
Boston $700 Jan-08-2005
Output
Store_name
Los Angeles
San Diego
Los Angeles
Boston
Distinct Keyword:
The SELECT keyword allows us to take all information from a column (or columns) on
a table. Of course, there is probability of redundancies. What if we only want to
select each DISTINCT element? This is easy to accomplish in SQL. All we need to do
is to add DISTINCT after SELECT. The syntax is as follows:
Output
Store_name
Los Angeles
San Diego
Boston
WHERE Syntax
To conditionally select the data from a table the WHERE clause is used . eg.if we
want to retrieve stores with sales above $1,000. To do this, we use the WHERE
keyword. The syntax is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "condition"
For example, to select all stores with sales above $1,000 in Table
Store_Information.
SQL command
SELECT store_name
FROM Store_Information
WHERE Sales > 1000
Notes: SQL uses single quotes around string values (most database systems will also
accept double quotes). Numeric values not be enclosed in quotes.
Output
store_name
Los Angeles
The following operators can be used with where clause:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Insert Command
The insert clause has one function; to insert data into a table. Insert
populates each table column with a value. Rows are inserted one
right after another into the coresponding column.
SQL Code:
Output
We mentioned setting up default or null values for table columns. Simply placing the
word default or null, in place of a value is the solution.
SQL Code:
Here's an example of how to insert more than one record at a time. Many web
developers will use the single example above along with HTML forms to continually
insert and update their SQL tables.
SQL Code:
This concept isn't widely supported by open source database programs, however they
do offer alternative methods to achieve the same goal. The idea is to insert similar
record values into 2 or more tables with one statement. Using the example from
above, we want to place Julie's information into our manager table as well as the
general employee table.
SQL Code:
INSERT ALL INTO employees (Lastname,Firstname,Title)
VALUES('Davis','Julie','manager')
INTO manager (training,salary)
VALUES ('yadayada','22500');
Update Command
Syntax:
UPDATE employees
SET Lastname = 'Fletcher' WHERE Firstname = 'David';
Output
With the use of operators and expressions, update allows for the manipulation of
several rows at once.
Syntax:
UPDATE employees
SET Title = UPPER(Title);
Output
ID Lastname Firstname Title
1 Fletcher David CREW
2 Hively Jessica CREW
9 Hicks Freddy CREW
10 Harris Joel CREW
11 Davis Julie MANAGER
Note:-By using UPPER expression we changed our Title field to all capital letters.
Delete may use with SQL operators as well as subqueries to delete any or all rows
that apply to our conditional.
Syntax
Truncate removes all the rows from the table and cannot be Rollbacked, while delete
removes all or specific rows from table and can be rollbacked. Truncate is used for
HUGE databases & Delete will work efficiently on small database table.
Syntax:
TRUNCATE TABLE employees;
Order By Command
The order by statement allows for table column range. It allows for ascending or
descending lists of column values, permitting SQL to reorder your table rows for the
purpose of viewing.
Syntax:
Output:-
Syntax:
WHERE keyword might be used to conditionally select data from a table. This
condition can be a simple condition or it can be a compound condition.Compound
conditions are made up of multiple simple conditions connected by AND/OR. There
is no limit to the number of conditions that can be present in a single SQL
statement.
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{[AND|OR] "simple condition"}+
Note:-The {}+ means that the expression inside the bracket will occur one or many
times.AND and OR can be used interchangeably. In addition,to indicate the order of
the condition we may use the parenthesis sign ().
e.g. we may wish to select all store_name with sales greater than $1,000 or all
stores with sales less than $500 but greater than $275 in Table Store_Information,
Output
store_name
Los Angeles
San Francisco
SQL In Operator
In is a special kind of operator which uses with where clauses. In the where
expression only one value is allowed to be sent through the query. With help of in
operator you can send multiple values in the where clause.
Syntax
Let's you wish to select all records for the Los Angeles and the San Diego stores in
Table Store_Information,
The Values inside parenthesis can be one or more, with each values separated by
comma. Values can be characters or numerical. If there is only one value inside the
parenthesis, then command is equivalent to :-
Output
SQL - Between
Syntax:
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'
It select all rows whose column has a value between 'value1' and 'value2'.
For example,to select all sales information between January 6, 2005, and January 10,
2005, in Table Store_Information
Syntax
SELECT *
FROM Store_Information
WHERE Date BETWEEN 'Jan-06-2005' AND 'Jan-10-2005'
Output
SQL Alias
Column Alias
Table Alias.
Syntax:-
Syntax :-
Column aliases exist to organizing output.In the previous example, whenever there is
total sales, it is listed as SUM(sales). While this is understandable, we can have many
cases where the column heading can be complicated (especially if it involves several
arithmetic operations). Using a column alias its make the output much more
readable.
Second is the table alias.This is accomplished by putting an alias directly after the
table name in the FROM clause. This is convenient when you want to obtain
information from two separate tables ('perform joins'). The advantage of using a
table alias when doing joins is readily apparent when we talk about joins.
Both types of aliases are placed directly after the item they alias for, separate by a
white space. We again use our table, Store_Information,
Syntax
Output
Notice that difference in the result that the column titles are now different. That is
the result of using the column alias. Notice that instead of the somewhat cryptic
"Sum(Sales)", we now have "Total Sales", which is much more understandable, as
the column header. The advantage of using a table alias is not visible in this
example. However, they will become evident in the Join Section
SQL Join
To create a single table the join clause combines columns of one table to that of
another. Join matches up a column with one table to a column in another. A join
query does not alter table, but temporarily combines data from each table to be
viewed as a single table.Mainly three types of join statements:-
Inner/Equi Join
Left Join
Right Join
Inner Join :-
An inner join returns all matching rows.For example given below
Table:-Store_Information
Table:-Geography
Region_name Store_name
East Boston
East New York
West Los Angeles
West San Diego
Let us we want to find out sales by region. For geting the sales information by
region, we have to combine the information from the two tables.Examining the two
tables, we find that they are linked via the common field, "store_name". First present
the SQL Query and then explain the use:
REGION SALES
East $700
West $2050
The first two lines tell SQL to select two fields, the first one is the field "region_name"
from table Geography (aliased as REGION), and the second one is the sum of the
field "Sales" from table Store_Information (aliased as SALES). Notice how the table
aliases are used here: Geography is aliased as A1, and Store_Information is aliased
as A2. Without the aliasing, the first line would become
which is much more bulky. In essence, table aliases make the entire SQL statement
easier to understand, especially when multiple tables are included.
Next, we turn our attention to line 3, the WHERE statement. This is where the
condition of the join is specified. In this case, we want to make sure that the content
in "store_name" in table Geography matches that in table Store_Information, and the
way to do it is to set them equal. This WHERE statement is essential in making sure
you get the correct output. Without the correct WHERE statement, a Cartesian Join
will result. Cartesian joins will result in the query returning every possible
combination of the two (or whatever the number of tables in the FROM statement)
tables. In this case, a Cartesian join would result in a total of 4 x 4 = 16 rows being
returned.
Previously, we had looked at inner join, where we select rows common to the
participating tables to a join. One case is that if we are interested in selecting
elements in a table regardless of whether they are present in the second table? We
will now need to use the SQL OUTER JOIN command.
Example:
The syntax for performing an outer join in SQL is database-dependent. For example,
in Oracle, we will place an "(+)" in the WHERE clause on the other side of the table
for which we want to include all the rows.
Table:-Store_Information
Table:-Geography
Region_name Store_name
East Boston
East New York
West Los Angeles
West San Diego
If we want to find out sales by region. We see that table Geography includes
information on regions and stores, and table Store_Information contains sales
information for each store. To get the sales information by region, we have to
combine the information from the two tables. Examining the two tables, we find that
they are linked via the common field, "store_name".
SELECT A1.store_name, SUM(A2.Sales) SALES
FROM Geography A1, Store_Information A2
WHERE A1.store_name = A2.store_name (+)
GROUP BY A1.store_name
Output:-
Store_name SALES
Boston $700
New York
Los Angeles $1800
San Diego $250
Note: When there is no match on the second table NULL is returned . In this case,
"New York" does not appear in the table Store_Information, thus its corresponding
"SALES" column is NULL.
SQL Union
SQL UNION combine the results of two queries together. In this respect, UNION is
similar to JOIN in that they are both used to related information from multiple
tables. One restriction of UNION is that all corresponding columns need to be of the
same data type and UNION only select distinct values.
Syntax:
[SQL Statement 1]
UNION
[SQL Statement 2]
Table Store_Information
Table Internet_Sales
Date Sales
Jan-07-2005 $250
Jan-10-2005 $535
Jan-11-2005 $320
Jan-12-2005 $750
If we want to find out all the dates where there is a sales transaction.We use the
following SQL statement:
Output:
Date
Jan-05-2005
Jan-07-2005
Jan-08-2005
Jan-10-2005
Jan-11-2005
Jan-12-2005
Syntax :
Output :
Date
Jan-05-2005
Jan-07-2005
Jan-08-2005
Jan-08-2005
Jan-07-2005
Jan-10-2005
Jan-11-2005
Jan-12-2005
SQL Subqueries
Subqueries are queries placed within an existing SQL statement. MySQL offers a very
limited support for subqueries, however Oracle and DB2 fully support them. They
may exist in any of the following types of SQL statements.
Syntax:
SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE [Condition])
Example:
Table: Store_Information
Table: Internet_Sales
Date Sales
Jan-07-2005 $250
Jan-10-2005 $535
Jan-11-2005 $320
Jan-12-2005 $750
If we want to use a subquery to find the sales of all stores in the West region. Then
we use the following SQL statement:
Output:
SUM(Sales)
2050
Here instead of joining the two tables directly and then adding up only the sales
amount for stores in the West region, we use subquery to find out which stores are in
the West region and then add the sales amount for these stores.
SQL Dates
SQL - Timestamp
A timestamp servers as the catch all for dates and times. Retrieving a timestamp is
very simple and the result can be manipulated in nearly every way possible.
Syntax:
Select Current_Timestamp;
Return a Timestamp:
2005-06-22 11:33:11.840
Tables are the structure where data is stored in the database. In most cases, there is
no way for the database vendor to know ahead of time what your data storage needs
are, then tables in the database makes itself. Many database tools allow you to
create tables automatically,but always tables are the container of all the data, it is
important to include the CREATE TABLE syntax in this tutorial.
Tables are divided into rows and columns. Each row represents one piece of data,
and each column represent a component of piece of data.Example, if we have a table
for recording customer information, then the columns may include information such
as First Name, Last Name, birth Date, Address, City, Country, and so on. As a result,
when we specify a table, we include the column headers and the data types for that
particular column.
Data comes in a variety of forms. It could be an integer (such as 1), a real number
(such as 0.55), a date/time expression (such as '2000-JAN-25 03:22:22'),a string
(such as 'sql'), or even in binary format. When we specify a table, we need to specify
the data type associated with each column (i.e., we will specify that 'First Name' is of
type char(40) - meaning it is a string with 40 characters). One thing to note is that
different relational databases allow for different data types.
Syntax
Example
This principle applies for retrieving data from a database table. Without an index, the
database system reads through the entire table (this process is called a 'table scan')
to locate the desired information. With the proper index the database system can
then first go through the index to find out where to retrieve the data, and then go to
these locations directly to get the needed data. This is much faster.
Therefore, it is often desirable to create indexes on tables. An index can cover one or
more columns.
Syntax
Example
Primary Key
A primary key is used to uniquely identify each row in a table. It can either be part of
the actual record itself , or it can be an artificial field (one that has nothing to do with
the actual record). A primary key consist of one or more fields on a table. When
multiple fields are used as a primary key then it is called composite key.
Primary keys can be specified either when the table is created or by changing the
existing table structure with alter command.
Foreign Key
A foreign key is a field that points to the primary key of another table. The purpose
of the foreign key is to ensure referential integrity means only values that are
supposed to appear in the database are permitted.
For example, say we have two tables, a CUSTOMER table that includes all customer
data, and an ORDERS table that includes all customer orders. The constraint here is
that all orders must be associated with a customer that is already in the CUSTOMER
table. In this case, we will place a foreign key on the ORDERS table and have it relate
to the primary key of the CUSTOMER table. By this way, we can ensure that all
orders in the ORDERS table are related to a customer in the CUSTOMER table. In
other words, the ORDERS table cannot contain information on a customer that is not
in the CUSTOMER table.
Table CUSTOMERS
Table ORDERS
In the above example, the Customer_SID column in the ORDERS table is a foreign
key pointing to the SID column in the CUSTOMER table.
Syntax
Drop Index
You can delete an existing index in a table with the DROP INDEX statement.
Syntax: MySQL
To delete a database:
Once a table is created in the database, there are many condition where we have to
change the structure of the table.
Add a column
Drop a column
Change a column name
Change the data type for a column
changing the primary key specification
Syntax
If we want to add a column called "Gender" to this table. Syntax given below:
If we want to change the data type for "Addr" to char(30).Syntax given below:
SQL Functions
A function is a special type of command that return a single value.
Types of Functions
The basic types of functions are:-
Aggregate functions
It operate against a collection of values, but return a single Value.
Scalar functions
It operate against a single value, and return a single value based on the input
value.Functions like CURRENT_TIME for example, do not require any
arguments.
Syntax:
Aggregate Functions
It return a single value based upon a set of other values. If used among many other
expressions in the item list of a SELECT statement, the SELECT must have a GROUP
BY clause. No GROUP BY clause is required if the aggregate function is the only value
retrieved by the SELECT statement
Supported aggregate functions are:
Function Usage
AVG(expression) Computes the average value of a column by the expression
COUNT(expression) Counts the rows defined by the expression
COUNT(*) Counts all rows in the specified table or view
MIN(expression) Finds the minimum value in a column by the expression
MAX(expression) Finds the maximum value in a column by the expression
SUM(expression) Computes the sum of column values by the expression
Example:
Scalar Functions
Different categories of Scalar Function are:-
Built-in Function
Date & Time Function
Numeric Function
String Function
Function Description
UCASE(c) Converts a field to upper case
LCASE(c) Converts a field to lower case
MID(c,start[,end]) Extract characters from a text field
LEN(c) Returns the length of a text field
Returns the numeric position of a named character
INSTR(c,char)
within a text field
LEFT(c,number_of_char) Return the left part of a text field requested
RIGHT(c,number_of_char) Return the right part of a text field requested
Rounds a numeric field to the number of decimals
ROUND(c,decimals)
specified
MOD(x,y) Returns the remainder of a division operation
NOW() Returns the current system date
FORMAT(c,format) Changes the way a field is displayed
DATEDIFF(d,date1,date2) Used to perform date calculations
Group By clause
When Aggregate functions (like SUM) called it return the aggregate of all column
values.It was impossible to find the sum for each individual group of column values
so Group By clause used.
Syntax:
Output
Store_name SUM(Sales)
Los Angeles $1800
San Diego $250
Boston $700
The GROUP BY keyword is used when selecting multiple columns from tables and at
least one arithmetic operator appears in the SELECT statement.
Having Clause
To limit the output based on the corresponding sum (or any other aggregate
functions). For example, we might want to see only the stores with sales over
$1,500. Instead of using the WHERE clause in the SQL statement, though, we need
to use the HAVING clause, which is reserved for aggregate functions. The HAVING
clause is placed near the end of the SQL statement. SQL statement with the HAVING
clause may or may not include the GROUP BY clause.
Output
store_name SUM(Sales)
Los Angeles $1800
To create a make-table query means for making backup copies of tables and reports,
or for archiving records.
Syntax
The example given below makes a backup copy of the "Persons" table:
If you only want to copy a few fields not copy whole Table, you can do so by listing
them after the SELECT statement. The following query creates a Fiddlers table by
extracting the names of fiddlers from a Musicians table:
The fields which you copy into a new table need not come from just one table. You
can copy from multiple tables as demonstrated in the next example which selects
fields from the two tables Suppliers and Products to create a new table for Mexican
Suppliers:
The SELECT...INTO statement doesn't define a primary key for the new table, so you
may want to do that manually.
View?
Syntax:
Views may be considered as virtual tables. Generalize way a table has a set of
definition, and it physically stores the data. A view also has a set of definitions, which
is build on top of table(s) or other view(s), and it does not physically store the data.
Example:
TABLE Customer
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date)
and we want to create a view called V_Customer that contains only the First_Name,
Last_Name, and Country columns from this table, we would type in,
View V_Customer
(First_Name char(50),
Last_Name char(50),
Country char(25))
Table:Store_Information
Table: Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
If we want to build a view that has sales by region information. We would issue the
following SQL statement:
It gives a view called V_REGION_SALES, that has been defined to store sales by
region records. If we want to find out the content of this view then following query:
SQL Summary
Now you have been introduced to the standard language of SQL . including the
client/server systems, relational database and Web-based database systems, all of
which are fundamental of understanding of SQL.
The database that will be used during your course of study was also introduced.
The database, which you have seen has consisted of a few tables, which are related
to one another, and the data that each table contains at this point. You should
have acquired some concept of a modern database and overall background
knowledge of the fundamentals of SQL.
This tutorial also taught the how to access and manipulat database systems.
You have learned how to execute queries,insert new records, retrieve data, delete
records and update records in a database with SQL.