What Is SQL?: Insert Into Tablename (Fieldname, Fieldname, Fieldname) Values (@fieldname, @fieldname, @fieldname)
What Is SQL?: Insert Into Tablename (Fieldname, Fieldname, Fieldname) Values (@fieldname, @fieldname, @fieldname)
What is SQL?
SQL (pronounced "sequel ") stands for Structured Query Language. SQL is used to
communicate with a database. SQL statements are used to perform tasks such as CRUD
operations over data in a database. Some common relational database management
systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc.
Although most database systems use SQL, most of them also have their own additional
proprietary extensions that are usually only used on their system. However, the standard
SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can
be used to accomplish almost everything that one needs to do with a database
TABLE BASICS
A relational database system contains one or more objects called tables. They are
uniquely identified by their names and are comprised of columns and rows. Columns
contain the column name, data type, and any other attributes for the column. Rows
contain the records or data for the columns.
Importing Data
You can import data into SQLScope from another data source by using the Insert
command
Creating Tables
To create a new table, enter the keywords create table followed by the table name,
followed by an open parenthesis, followed by the first column name, followed by the data
type for that column, followed by any optional constraints, and followed by a closing
parenthesis. It is important to make sure you use an open parenthesis before the
beginning table, and a closing parenthesis after the end of the last column definition.
Make sure you seperate each column definition with a comma. All SQL statements
should end with a ";".
While creating tables,user should specify type of column it is going to have , here are
types available :
1
SQL
Explanation:
Examples:
Char -- a character string
Float -- a number
Date -- a date field
Logical -- a logical field
You can also limit the type of information a table / a column can hold. This is done through the
CONSTRAINT keyword
You can place constraints to limit the type of data that can go into a table. Such constraints can
be specified when the table when the table is first created via the CREATE TABLE statement, or
after the table is already created via the ALTER TABLE statement
• NOT NULL Constraint: Ensures that a column cannot have NULL value. (By default, a
column can hold NULL)
• DEFAULT Constraint: Provides a default value for a column when none is specified.
• UNIQUE Constraint: Ensures that all values in a column are different.
• CHECK Constraint: Makes sure that all values in a column satisfy certain criteria.( Once
defined, the database will only insert a new row or update an existing row if the new
value satisfies the CHECK constraint. The CHECK constraint is used to ensure data
quality.)
• Primary Key Constraint: Used to uniquely identify a row in the table.
• Foreign Key Constraint: Used to ensure referential integrity of the data.
Alter Table
Once a table is created in the database, there are many occasions where one may wish to
change the structure of the table. In general, the SQL syntax for ALTER TABLE is
2
SQL
1.Add/Modify/Rename/Drop column
2. Add/Drop Index
3. Add/Drop Constraint
ALTER TABLE "table_name" Change "column 1" "column 2" ["Data Type"]
The insert statement is used to insert or add a row of data into the table.
To insert records into a table, enter the key words insert into followed by the table name,
followed by an open parenthesis, followed by a list of column names separated by
commas, followed by a closing parenthesis, followed by the keyword values, followed by
the list of values enclosed in parenthesis. The values that you enter will be held in the
rows and they will match up with the column names that you specify. Strings should be
enclosed in single quotes, and numbers should not
Selecting Data
The select statement is used to query the database and retrieve selected data that match
the criteria that you specify. The column names that follow the select keyword determine
which columns will be returned in the results. You can select as many column names that
you'd like, or you can use a "*" to select all columns.
The where clause (optional) specifies which data values or rows will be returned or
displayed, based on the criteria described after the keyword where.
You can add multiple criteria to your Where clauses by using "and" or "or."
3
SQL
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal to
LIKE *See note below
The LIKE pattern matching operator can also be used in the conditional selection of the
where clause. Like is a very powerful operator that allows you to select only rows that are
"like" what you specify. The percent sign "%" can be used as a wild card to match any
possible character that might appear before or after the characters specified
HAVING
The SQL HAVING clause is used to restrict conditionally the output of a SQL
statement, by a SQL aggregate function used in your SELECT list of columns
You can't specify criteria in a SQL WHERE clause against a column in the SELECT list for
which SQL aggregate function is used. For example the following SQL statement will
generate an error:
The SQL HAVING clause is used to do exactly this, to specify a condition for an aggregate
function which is used in your query:
The above SQL statement will select all employees and the sum of their respective hours,
as long as this sum is greater than 24. The result of the SQL HAVING clause can be seen
below:
4
SQL
Employee Hours
John Smith 25
Tina Crown 27
DISTINCT
The SQL DISTINCT clause is used together with the SQL SELECT keyword, to return
a dataset with unique entries for certain database table column.
LIKE
The SQL LIKE clause is very useful when you want to specify a search condition within
your SQL WHERE clause, based on a part of a column contents.
The '%' is a so called wildcard character and represents any string in our pattern.
Another wildcard character is '_' representing any single character.
IN
The SQL IN clause allows you to specify discrete values in your SQL WHERE search
criteria.
SELECT Column1, Column2, Column3, FROM Table1 WHERE Column1 IN (Valu1, Value2, …)
BETWEEN
The SQL BETWEEN & AND keywords define a range of data between 2 values
SELECT Column1, Column2, Column3, FROM Table1 WHERE Column1 BETWEEN Value1
AND Value2
The 2 values defining the range for SQL BETWEEN clause can be dates, numbers or
just text
ALIASES
SQL aliases can be used with database tables and with database table columns, depending
on task you are performing.
GROUP BY
The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to
provide means of grouping the result dataset by certain database table column(s).
5
SQL
Consider the following database table called EmployeeHours storing the daily hours for each
employee of a factious company:
If the manager of the company wants to get the simple sum of all hours worked by all
employees, he needs to execute the following SQL statement:
But what if the manager wants to get the sum of all hours for each of his employees?
To do that he need to modify his SQL query and use the SQL GROUP BY statement:
Employee Hours
John Smith 25
Allan Babel 24
Tina Crown 27
As you can see we have only one entry for each employee, because we are grouping by the
Employee column.
The SQL GROUP BY clause can be used with other SQL aggregate functions, for example
SQL AVG:
6
SQL
Employee Hours
John Smith 8.33
Allan Babel 8
Tina Crown 9
In our Employee table we can group by the date column too, to find out what is the total
number of hours worked on each of the dates into the table:
Date Hours
5/6/2004 24
5/7/2004 27
5/8/2004 25
Ordering Rows
If you want to see your data displayed in sequence, you must add an Order By clause to
your Select statement.By default it will display in ascending, however we can opt for
descending using “DESC”
7
SQL
When ordering your data, you can have multiple sort levels.
Joining Tables
Explanation:
When you join two or more tables, a good idea is to precede the field
names with the table names. This is not mandatory unless the same field name is
found in more than one table.
If you precede the field name with a table name, place a period between
the two names. For example, tablename.fieldname.
You must specify which fields are being joined.
If you do not specify which fields are being joined, the result is what is
commonly referred to as a "Cartesian join" in which all rows in the first table are
joined with all rows in the second table.
You can give each table name an alias, or alternative table name. When
you assign an alias, you can then refer to the table by using its alias.
Updating Records
The update statement is used to update or change records that match a specified criteria.
This is accomplished by carefully constructing a where clause
Start transaction;
Update tablename
set fieldname = value
where fieldname = value;
Rollback work;
Commit work;
Explanation:
8
SQL
Issue a Start Transaction command before updating your table. This will
allow you to roll back the changes, if necessary. If you do not issue a Start
Transaction command, you will not be able the roll back your work.
If you find that you have updated a row in error, execute the Rollback
Work command.
When you are satisfied with your changes, issue the Commit Work
command.
Use a Where clause to specify which rows will be updated. If you do
not include a Where clause, all rows will be updated.
Remember to end each command with a semicolon
Inserting Rows
Explanation:
When inserting data, use the Start Transaction command so that any errors
can be rolled back.
You must specify the values to be inserted.
When performing an insert, enclose character values in single quotes.
Do not enclose numeric values in single quotes.
Use the Rollback Work command to undo changes.
Use the Commit Work command to finalize changes
Deleting Records
The delete statement is used to delete records or rows from the table
To delete an entire record/row from a table, enter "delete from" followed by the table
name, followed by the where clause which contains the conditions to delete. If you leave
off the where clause, all records will be deleted.
Drop a Table
The drop table command is used to delete a table and all rows in the table.
Explanation:
9
SQL
If you do not include a Where clause, all of the rows in the table will be
deleted.
Every table has a primary key -- a field or combination of fields that
uniquely identify each row in the table. VendId is the primary key for the vendor
table. Each vendor is uniquely identified by the vendor Id. RefNbr is the primary
key for APDoc.
If you want to delete a single row of data, you can refer to the row in the
Where clause by using the primary key.
When deleting data, use the Start Transaction command so that any errors
can be rolled back.
Use the Rollback Work command to undo changes.
Use the Commit Work command to finalize changes
To delete an entire table including all of its rows, issue the drop table command
followed by the tablename. drop table is different from deleting all of the records in the
table. Deleting all of the records in the table leaves the table including column and
constraint information. Dropping the table removes the table definition as well as all of
its rows.
Truncate Table
View
A view is a virtual table. A view consists of rows and columns just like a table. The difference
between a view and a table is that views are definitions built on top of other tables (or views), and
do not hold data themselves. If data is changing in the underlying table, the same change is
reflected in the view. A view can be built on top of a single table or multiple tables. It can also be
built on top of another view.
Advantages:
1. Ease of use: A view hides the complexity of the database tables from end users. Essentially
we can think of views as a layer of abstraction on top of the database tables.
2. Space savings: Views takes very little space to store, since they do not store actual data.
3. Additional data security: Views can include only certain columns in the table so that only the
non-sensitive columns are included and exposed to the end user. In addition, some databases
allow views to have different security settings, thus hiding sensitive data from prying eyes
"SQL Statement" can be any of the SQL statements we have discussed in this tutorial.
Index
Indexes help us retrieve data from tables quicker. Let's use an example to illustrate this point: Say
we are interested in reading about how to grow peppers in a gardening book. Instead of reading
the book from the beginning until we find a section on peppers, it is much quicker for us to go to
10
SQL
the index section at the end of the book, locate which pages contain information on peppers, and
then go to these pages directly. Going to the index first saves us time and is by far a more
efficient method for locating the information we need.
Therefore, it is often desirable to create indexes on tables. An index can cover one or more
columns.
1.Build index on columns of integer type :Integers take less space to store, which means the
query will be faster. If the column you want to build an index for is not of type integer, consider
creating a surrogate integer key (or simply a surrogate column of type integer) which maps one-
to-one to the column you want to build the index for.
2.Keep index as narrow as possible : Narrower indexes take less space, require less time to
process, which in turn means the query will run faster.
3.Column order is important : For indexes covering multiple columns, the order of the columns
in the index is important. The best practice is to use the column with the lowest cardinality first,
and the column with the highest cardinality last. Recall cardinality means the number of distinct
values for that column. So, if "SELECT DISTINCT (COLUMN1) FROM TABLE_NAME;" returns 5,
that means the cardinality for COLUMN1 is 5.
4. Make sure the column you are building an index for is declared NOT NULL : This can
decrease the size of the index, which in turn will speed up the query.
There is no strict rule on how to name an index. The generally accepted method is to place a
prefix, such as "IDX_", before an index name to avoid confusion with other database objects. It is
also a good idea to provide information on which table and column(s) the index is used on.
NULL
In SQL, NULL means that data does not exist. NULL does not equal to 0 or an empty string. Both
0 and empty string represent a value, while NULL has no value at all.
Aggregate functions such as SUM, COUNT, AVG, MAX, and MIN exclude NULL values. This is
not likely to cause any issues for SUM, MAX, and MIN. However, this can lead to confusion with
AVG and COUNT.
Table Sales_Data
store_name Sales
Store A 300
Store B 200
Store C 100
Store D NULL
11
SQL
COUNT (Sales) = 3
Note that the AVG function counts only 3 rows (the NULL row is excluded), so the average is
600 / 3 = 200, not 600 / 4 = 150. The COUNT function also ignores the NULL rolw, which is why
COUNT (Sales) = 3.
ISNULL Function
the ISNULL() function is used to test whether an expression is NULL. If the expression is NULL,
this function returns 1. Otherwise, this function returns 0.
Table Sales_Data
store_name Sales
Store A 300
Store B NULL
returns 400. This is because NULL has been replaced by 100 via the ISNULL function
NVL Function
The NVL() function is used to replace NULL value with another value
Table Sales_Data
store_name Sales
Store A 300
Store B NULL
Store C 150
12
SQL
returns 550. This is because NULL has been replaced by 100 via the ISNULL function, hence the
sum of the 3 rows is 300 + 100 + 150 = 550.
NULLIF Function
The NULLIF function takes two arguments. If the two arguments are equal, then NULL is
returned. Otherwise, the first argument is returned
For example, let's say we have a table that tracks actual sales and sales goal as below:
Table Sales_Data
We want to show NULL if actual sales is equal to sales goal, and show actual sales if the two are
different. To do this, we issue the following SQL statement:
Store_name NULLIF(Actual,Goal)
Store A NULL
Store B 40
Store C 25
Union
The purpose of the SQL UNION query is to combine the results of two queries together. In this
respect, UNION is somewhat 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. Also, when using UNION, only distinct values are selected (similar to SELECT
DISTINCT).
Table Store_Information
13
SQL
Table Internet_Sales
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there is a sales transaction. To do so, we use the
following SQL statement:
Result:
Date
Jan-05-1999
Jan-07-1999
Jan-08-1999
Jan-10-1999
Jan-11-1999
Jan-12-1999
Please note that if we type "SELECT DISTINCT Date" for either or both of the SQL statement, we
will get the same result set.
Union All
The purpose of the SQL UNION ALL command is also to combine the results of two queries
together. The difference between UNION ALL and UNION is that, while UNION only selects
distinct values, UNION ALL selects all values.
Let's use the same example as the previous section to illustrate the difference. Assume that we
have the following two tables,
Table Store_Information
14
SQL
Table Internet_Sales
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there is a sales transaction at a store as well as all the
dates where there is a sale over the internet. To do so, we use the following SQL statement:
Result:
Date
Jan-05-1999
Jan-07-1999
Jan-08-1999
Jan-08-1999
Jan-07-1999
Jan-10-1999
Jan-11-1999
Jan-12-1999
Intersect
Similar to the UNION command, INTERSECT also operates on two SQL statements. The
difference is that, while UNION essentially acts as an OR operator (value is selected if it appears
in either the first or the second statement), the INTERSECT command acts as an AND operator
(value is selected only if it appears in both statements).
Table Store_Information
15
SQL
Table Internet_Sales
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there are both store sales and internet sales. To do
so, we use the following SQL statement:
Result:
Date
Jan-07-1999
Please note that the INTERSECT command will only return distinct values.
Minus
The MINUS operates on two SQL statements. It takes all the results from the first SQL statement,
and then subtract out the ones that are present in the second SQL statement to get the final
answer. If the second SQL statement includes results not present in the first SQL statement, such
results are ignored.
Table Store_Information
Table Internet_Sales
16
SQL
Date Sales
Jan-07-1999 $250
Jan-10-1999 $535
Jan-11-1999 $320
Jan-12-1999 $750
and we want to find out all the dates where there are store sales, but no internet sales. To do so,
we use the following SQL statement:
Result:
Date
Jan-05-1999
Jan-08-1999
"Jan-05-1999", "Jan-07-1999", and "Jan-08-1999" are the distinct values returned from "SELECT
Date FROM Store_Information." "Jan-07-1999" is also returned from the second SQL
statement, "SELECT Date FROM Internet_Sales," so it is excluded from the final result set.
Please note that the MINUS command will only return distinct values.
Some databases may use EXCEPT instead of MINUS. Please check the documentation for your
specific database for the correct usage.
Subquery
It is possible to embed a SQL statement within another. When this is done on the WHERE or the
HAVING statements, we have a subquery construct
[Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also be a text
operator such as "LIKE", EXISTS
EXISTS simply tests whether the inner query returns any row. If it does, then the outer query
proceeds. If not, the outer query does not execute, and the entire SQL statement returns nothing.
Case
CASE is used to provide if-then-else type of logic to SQL. Its syntax is:
17
SQL
[ELSE "resultN"]
END
FROM "table_name"
Table Store_Information
if we want to multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San
Diego' by 1.5, we key in,
"New Sales" is the name given to the column with the CASE statement.
Result:
JOIN
The SQL JOIN clause is used whenever we have to select data from 2 or more tables.
There are 2 types of SQL JOINS – INNER JOINS and OUTER JOINS. If you don't put
INNER or OUTER keywords in front of the SQL JOIN keyword, then INNER JOIN is used.
In short "INNER JOIN" = "JOIN" (note that different databases have different syntax for
their JOIN clauses).
18
SQL
The INNER JOIN will select all rows from both tables as long as there is a match
between the columns we are matching on.
Example
The second type of SQL JOIN is called SQL OUTER JOIN and it has 2 sub-types
called LEFT OUTER JOIN and RIGHT OUTER JOIN.
The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword
in most databases), selects all the rows from the first table listed after the FROM clause,
no matter if they have matches in the second table.
The RIGHT OUTER JOIN or just RIGHT JOIN behaves exactly as SQL LEFT
JOIN, except that it returns all rows from the second table (the right table in our SQL
JOIN statement
In SQL, decimals are often referred to as point or floating-point numbers. These data types are
slightly different from the normal 'integer' data types.
Date values are stored in date table columns in the form of a timestamp. A SQL timestamp is a record
containing date/time data, such as the month, day, year, hour, and minutes/seconds. It's not much
different from the standard date format
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.
Strings range from a single word or character to large blocks of text including multiple paragraphs
and unique symbols. Set the table column type to VARCHAR or Text in order to incorporate string data
types into SQL tables.
Example
19
SQL
• (1/0)
• VARCHAR - ('Words or numbers')
• Text - ('Once upon a time...')
20