This is a word file for SQL COMMANDS and including some basic information regarding SQL. I hope it will help you a lot while doing SQL and its functions and commands.
1. 1
SQL Commands
Database
A database consists of one or more tables. A table is identified
by its name. A table is made up of columns and rows. Columns
contain the column name and data type. Rows contain the
records or data for the columns.
BasicSQL
Each record has a unique identifier or primary key. SQL, which
stands for Structured Query Language, is used to communicate
with a database. Through SQL one can create and delete tables.
Here are some commands:
CREATE TABLE - creates a new database table
ALTER TABLE - alters a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
2. 2
SQL also has syntax to update, insert, and delete records.
SELECT - get data from a database table
UPDATE - change data in a database table
DELETE - remove data from a database table
INSERT INTO - insert new data in a database table
FOURCOMPONENTSOF SQL:
DDL(data definition language)
DML(data manipulation language)
DCL(data control language)
DQL(data query language)
3. 3
CREATETABLE
The CREATE TABLE statement is used to create a new table.
The format is:
CREATE TABLE tablename
(column1 data type,
column2 data type,
column3 data type);
char(size): Fixed length character string.
varchar(size): Variable-length character string. Max size is
specified in parenthesis.
number(size): Number value with a max number of
columns specified in parenthesis
date: Date value
number(size,d): A number with a maximum number of
digits of "size" and a maximum number of "d" digits to the
right of the decimal
4. 4
INSERTVALUES
Once a table has been created data can be inserted using
INSERT INTO command.
INSERT INTO tablename
(col1, ... , coln)
VALUES (val1, ... , valn)
SELECT
The SELECT is used to query the database and retrieve selected
data that match the specific criteria that you specify:
SELECT column1 [, column2, ...]
FROM tablename WHERE condition
The conditional clause can include these operators
= Equal
> Greater than
< Less than
5. 5
>= Greater than or equal
<= Less than or equal
<> Not equal to
LIKE pattern matching operator
SELECT * FROM tablename
returns all the data from the table.
Use single quotes around text values (most database systems
will also accept double quotes). Numerical values should not be
enclosed in quotes.
LIKE matches a pattern. The wildcard % is used to denote 0 or
more characters.
'A%' : matches all strings that start with A
'%a' : matches all strings that end with a
'%a%' : matches all strings that contain an a
UPDATE
To change the data values in a pre existing table, the UPDATE
command can be used.
UPDATE tablename
6. 6
SET colX = valX [, colY = valY, ...]
WHERE condition
DELETE
The DELETE command can be used to remove a record(s) from
a table.
DELETE FROM tablename
WHERE condition
To delete all the records from a table without deleting the table
do
DELETE * FROM tablename
DROP
To remove an entire table from the database use the DROP
command.
DROP TABLE tablename
7. 7
ORDER BY
ORDER BY clause can order column name in either ascending
(ASC) or descending (DESC) order.
ORDER BY col_name ASC
AND / OR
AND and OR can join two or more conditions in a WHERE
clause. AND will return data when all the conditions are true.
OR will return data when any one of the conditions is true.
IN
IN operator is used when you know the exact value you want to
return for at least one of the columns
SELECT * FROM table_name WHERE col_name IN (val1,
val2, ...)
BETWEEN/AND
8. 8
The BETWEEN ... AND operator selects a range of data
between two values. These values can be numbers, text, or dates.
SELECT * FROM table_name WHERE col_name BETWEEN
val1 AND val2
SQL DISTINCTClause:
SELECT DISTINCT column1, column2....columnN
FROM table_name;
SQL DESCStatement:
DESC table_name;
JOIN
There are times when we need to collate data from two or more
tables. That is called a join. Tables in a database are related to
each other through their keys. We can associate data in various
tables without repeating them. For example we could have a
table called Customers which could have information about
9. 9
customers like their name, address, phone numbers. We could
have another table called Products that has information
regarding the products like part number, product name,
manufacturer, number in stock, unit price. A third table called
Orders could have information regarding what product was
ordered, by whom, the date the order was placed, and quantity.
Here are the tables:
Customers
Cust_ID FirstName LastName Address Phone
01 Mickey Mouse
123
Gouda
St.
456-
7890
02 Donald Duck
325
Eider
Ln.
786-
2365
Products
Part_No Name Manufacturer In_Stock Price
20-45 Hammer Stanley 57 3.50
21-68 ScrewDriver DeVries 84 2.75
Orders
Order_No Part_No Cust_ID Date Quantity
2005-27 21-68 02
31
Oct
2
10. 10
2005
2005-34 20-45 01
02
Nov
2005
3
We can obtain information on who has ordered what:
SELECT Customers.FirstName, Customers.LastName,
Products.Name
FROM Customers, Products, Orders
WHERE Customers.Cust_ID = Orders.Cust_ID AND
Products.Part_No = Orders.Part_No
We can select data from two tables with INNERJOIN. The INNER
JOIN returns all rows from both tables where there is a match. If
there are rows in Customers that do not have matches in Orders,
those rows will not be listed.
SELECT Customers.FirstName, Customers.LastName,
Orders.Date
FROM Customers
11. 11
INNER JOIN Orders
ON Customers.Cust_ID = Orders.Cust_ID
The LEFTJOINreturns all the rows from the first table
(Customers), even if there are no matches in the second table
(Orders). If there are rows in Customers that do not have
matches in Orders, those rows also will be listed.
SELECT Customers.FirstName, Customers.LastName,
Orders.Date
FROM Customers
LEFT JOIN Orders
ON Customers.Cust_ID = Orders.Cust_ID
The RIGHTJOINreturns all the rows from the second table
(Orders), even if there are no matches in the first table
(Customers). If there had been any rows in Orders that did not
have matches Customers, those rows also would have been
listed.
SELECT Customers.FirstName, Customers.LastName,
Orders.Date
12. 12
FROM Customers
RIGHT JOIN Orders
ON Customers.Cust_ID = Orders.Cust_ID
ALTER TABLE
With ALTER TABLE you can add or delete columns in an
existing table. When you add a column you must specify a data
type.
ALTER TABLE table_name
ADD col_name datatype
ALTER TABLE table_name
DROP COLUMN col_name
SQL ALTER TABLEStatement:
ALTER TABLE table_name {ADD|DROP|MODIFY}
column_name {data_ype};
13. 13
SQL ALTERTABLE Statement(Rename) :
ALTER TABLE table_name RENAME TO
new_table_name;
Wildcard
There are times when we want to match on a string pattern. To
do that, we will need to employ the concept of wildcard. In
SQL, there are two wildcards:
% (percent sign) represents zero, one, or more characters.
_ (underscore) represents exactly one character.
Wildcards are used with the LIKE keyword in SQL.
Below are some wildcard examples:
'A_Z': All string that starts with 'A', another character, and
end with 'Z'. For example, 'ABZ' and 'A2Z' would both
14. 14
satisfy the condition, while 'AKKZ' would not (because
there are two characters between A and Z instead of one).
'ABC%': All strings that start with 'ABC'. For example,
'ABCD' and 'ABCABC' would both satisfy the condition.
'%XYZ': All strings that end with 'XYZ'. For example,
'WXYZ' and 'ZZXYZ' would both satisfy the condition.
'%AN%': All strings that contain the pattern 'AN'
anywhere. For example, 'LOS ANGELES' and 'SAN
FRANCISCO' would both satisfy the condition.
'_AN%': All strings that contain a character, then 'AN',
followed by anything else. For example, 'SAN
FRANCISCO' would satisfy the condition, while 'LOS
ANGELES' would not satisfy the condition.
Like
LIKE is another keyword that is used in the WHEREclause.
Basically, LIKE allows you to do a search based on a pattern
rather than specifying exactly what is desired (as in IN) or
spell out a range (as in BETWEEN). The syntax is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN};
15. 15
SQLFunctions
There are several built-in functins in SQL. The basic function
types are:
Aggregate Functions: These are functions that operate
against a collection of values, but return a single value.
Scalar Functions: These functions operate against a single
value, and return a single value.
To use a built-in function the syntax is:
SELECT function (col_name) FROM table_name
COUNT
Is arithmetic function. This allowsus to count up the number of
row in a certain table. The syntax is,
SELECT COUNT("column_name")
FROM "table_name";
COUNTandDISTINCTcanbe used together in a statement to
retrieve the number of distinct entries in a table.
16. 16
Average
SQL uses the AVG() function to calculate the average of a
column. The syntax for using this function is,
SELECT AVG("column_name") FROM "table_name";
MAX
SQL uses the MAX function to find the maximum value in a
column. The syntax for using the MAX function is,
SELECT MAX ("column_name")
FROM "table_name";
MIN
SQL uses the MIN function to find the maximum value in a
column. The syntax for using the MIN function is,
SELECT MIN ("column_name")
FROM "table_name";
SUM
17. 17
The SUM function is used to calculate the total for a column. The
syntax is,
SELECT SUM("column_name")
FROM "table_name";
DATEDIFF
The DATEDIFF function is used to calculate the difference between
two days, and is used in MySQL and SQL Server. The syntax
for this date function is different between these two databases,
so each one is discussed below:
The usage for the DATEDIFF function in MySQL is:
DATEDIFF (expression1, expression2)
where the data type of <expression1> and <expression2> is
either DATE or DATETIME. The result is <expression1> -
<expression2>.
NOW
18. 18
Gives the current date.the syntax is:
Select Now() from tablename;
GROUPBY
The GROUP BY was added to SQL so that aggregate functions
could return a result grouped by column values.
SELECT col_name, function (col_name) FROM table_name
GROUP BY col_name
HAVING keyword was introduced because the WHERE
keyword could not be used. HAVING states a condition.
SELECT col_name, function (col_name) FROM table_name
GROUP BY col_name
HAVING function (col_name) condition value
19. 19
CREATEVIEW
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.
Views offer the following advantages:
1. Easeofuse: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. Spacesavings:Views takes very little space to store, since
they do not store actual data.
3. Additionaldatasecurity: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
20. 20
addition, some databases allow views to have different
security settings, thus hiding sensitive data from
prying eyes. A view is a virtual table that is a result of
SQL SELECT statement. A view contains fields from
one or more real tables in the database. This virtual
table can then be queried as if it were a real table.
CREATE VIEW view_name AS
SELECT col_name(s)
FROM table_name
WHERE condition
A view could be used from inside a query, a stored procedure, or
from inside another view. You can add functions and joins to a
view and present the data you want to the user.
SQL– INDEXES
Indexes are special lookup tables that the database search eng
ine can use to speed up data retrieval. Simply put,an index is a
pointer to data in a table. An index in a database is very similar
to an index in the back of a book.
21. 21
For example, if you want to reference all pages in a book that
discuss a certain topic, you first refer to the index,which lists all
topics alphabetically and are then referred to one or more
specific page numbers.
An index helps speed up SELECT queries and WHEREclauses, but
it slows down data input, with UPDATE and INSERT statements.
Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATEINDEX statement, which
allows you to name the index, to specify the table and which
column or columns to index, and to indicate whether the index is
in ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in
that the index prevents duplicate entries in the column or
combination of columns on which there's an index.
The CREATEINDEX Command
The basic syntax of CREATE INDEX is as follows:
CREATE INDEX index_name ON table_name;
22. 22
Single-ColumnIndexes
A single-column index is one that is created based on only one
table column. The basic syntax is as follows:
CREATE INDEX index_name
ON table_name (column_name);
UniqueIndexes
Unique indexes are used not only for performance, but also for
data integ rity. A unique index does not allow any
duplicate values to be inserted into the table. T he basic syntax is
as follows:
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);
CompositeIndexes
A composite index is an index on two or more columns of a
table. T he basic syntax is as follows:
CREATE INDEX index_name on table_name (column1,
column2);
Whether to create a sing le-column index or a composite index,
take into consideration the column(s) that you may use very
frequently in a query's WHERE clause as filter
23. 23
conditions.Should there be only one column used, a sing le-
column index should be the choice. Should there be two or more
columns that are frequently used in the WHERE clause as filters,
the composite index would be the best choice.
ImplicitIndexes
Implicit indexes are indexes that are automatically created by
the database server when an object is created.
Indexes are automatically created for primary key constraints
and unique constraints.
The DROPINDEXCommand
An index can be dropped using SQL DROP command. Care
should be taken when dropping an index because performance
may be slowed or improved.
T he basic syntax is as follows:
DROP INDEX index_name;
24. 24
When shouldindexes beavoided?
Although indexes are intended to enhance a database's
performance, there are times when they should be avoided. The
following guidelines indicate when the use of an index should be
reconsidered:
Indexes should not be used on small tables.
Tables that have frequent, large batch update or insert
operations.
Indexes should not be used on columns that contain a high
number of NULL values.
Columns that are frequently manipulated should not be indexed.
25. 25
Constraint
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 CREATETABLEstatement, or
after the table is already created via the ALTER TABLE statement.
Common types of constraints include the following:
NOTNULLConstraint: Ensures that a column cannot have
NULL value.
DEFAULTConstraint: Provides a default value for a column
when none is specified.
UNIQUEConstraint: Ensures that all values in a column are
different.
CHECKConstraint: Makes sure that all values in a column
satisfy certain criteria.
PrimaryKeyConstraint: Used to uniquely identify a row in the
table.
ForeignKeyConstraint: Used to ensure referential integrity of
the data.
26. 26
Each constraint is discussed in the following sections:
NOTNULL Constraint
By default, a column can hold NULL. If you do not want to allow
NULL value in a column, you will want to place the NOTNULL
constraint on this column. The NOTNULLconstraint specifies that
NULL is not an allowable value. For example, in the following
statement,
CREATE TABLE Customer (SID integer NOT NULL,
Last_Name varchar (30) NOT NULL, First_Name varchar(30));
DEFAULTConstraint
The DEFAULT constraint provides a default value to a column
when the INSERTINTO statement does not provide a specific value.
For example, if we create a table as below:
27. 27
CREATE TABLE Student
(Student_ID integer Unique,
Last_Name varchar (30),
First_Name varchar (30),
Score Integer DEFAULT 80);
UNIQUEConstraint
The UNIQUE constraint ensures that all values in a column are
distinct.
For example, in the following CREATETABLE statement,
CREATE TABLE Customer
(SID integer UNIQUE, Last_Name varchar (30),
First_Name varchar(30));
column "SID" has a UNIQUE constraint, and hence cannot include
duplicate values.
CHECKConstraint
28. 28
The CHECK constraint ensures that all values in a column satisfy
certain conditions. 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.
For example, in the following CREATETABLE statement,
CREATE TABLE Customer
(SID integer CHECK (SID > 0),
Last_Name varchar (30),
First_Name varchar(30));
Column "SID" has a constraint -- its value must only include
integers greater than 0.
Primary Key
A primary key is used to uniquely identify each row in a table.A
primary key can consist of one or more columns on a table.
When multiple columns are used as a primary key, they are
called a composite key. A primary key cannot be NULL, as it does
not make sense to use the NULLvalue to uniquely identify a
record. Therefore, the column that is set as a primary key or as
part of a primary key cannot be NULL.
29. 29
Primary keys can be specified either when the table is created
(using CREATETABLE) or by changing the existing table structure
(using ALTERTABLE).
Primary KeyOn OneColumn MySQL
CREATE TABLE Customer (SID integer, Last_Name
varchar(30), First_Name varchar(30), PRIMARY KEY (SID));
Primary KeyOn MultipleColumns
In the examples below, the composite primary key consists of
two columns, Birth_Date and Social_Security_Number.
MySQL
CREATE TABLE Customer_Composite_Key
(Last_Name varchar(30),
First_Name varchar(30),
Birth_Date datetime, Social_Security_Number integer,
PRIMARY KEY (Birth_Date, Social_Security_Number));
ForeignKey
30. 30
A foreign key is a column (or columns) that references a column
(most often the primary key) of another table. The purpose of
the foreign key is to ensure referential integrity of the data. In
other words, 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 ORDERStable that includes all
customer orders. Business logic requires that all orders must be
associated with a customer that is already in the CUSTOMER table.
To enforce this logic, we place a foreign key on the ORDERS table
and have it reference the primary key of the CUSTOMER table.
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.
The structure of these two tables will be as follows:
Table CUSTOMER
31. 31
Column Name Characteristic
SID Primary Key
Last_Name
First_Name
Table ORDERS
Column Name Characteristic
Order_ID Primary Key
Order_Date
Customer_SID Foreign Key
Amount
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. The following examples are operations that
violate the referential integrity of this relationship:
Inserting a row in the ORDERS table where Customer_SID
does not appear in the SID column in the CUSTOMERtable.
32. 32
Deleting a row from the CUSTOMER table where the SID of
the row to be delete is still present in the Customer_SID
column in the ORDERS table.
When these operations are attempted, the database would return
an error stating that referential integrity is violated.
MySQL
CREATE TABLE ORDERS
(Order_ID integer,
Order_Date date,
Customer_SID integer,
Amount double, Primary Key (Order_ID),
Foreign Key (Customer_SID) REFERENCES
CUSTOMER(SID));