SQL Commands Detailed
SQL Commands Detailed
__________________________________
..................................................................... 16
.............................................................................. 17
................................................................. 17
.................................................................................. 18
........................................................................... 21
....................................................................... 23
............................................................................... 24
.................................................................................. 24
.............................................................................. 24
............................................................................... 25
SQL FIRST() Workaround in SQL Server, MySQL and Oracle ..... 25
................................................................................ 26
................................................................................. 26
.................................................................................. 27
................................................................................. 27
.................................................................................. 27
............................................................................. 28
.............................................................................. 28
.................................................................................. 28
................................................................................... 28
............................................................................. 29
................................................................................. 29
........................................................................... 29
__________________________________
__________________________________
SQL commands
CustomerID
1
CustomerName
ContactName
Address
City
PostalCode
Country
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Germany
Mxico D.F.
05021
Mexico
Mxico D.F.
05023
Mexico
Thomas Hardy
London
WA1 1DP
UK
Berglunds
snabbkp
Christina
Berglund
Berguvsvgen 8
Lule
S-958 22
Sweden
Ana
Trujillo
Emparedados
y Ana Trujillo
helados
Antonio
Taquera
Moreno
Avda.
de
Constitucin
2222
la
Command
Function
__________________________________
__________________________________
In a table, a column may contain many duplicate values; and sometimes you only want to
list the different (distinct) values.
The DISTINCT keyword can be used to return only distinct (different) values.
Command
Function
The WHERE clause is used to extract only those records that fulfill a specified criterion.
Command
Function
Operator
Description
Equal
<>
Not equal. Note: In some versions of SQL this operator may be written as !=
>
Greater than
<
Less than
>=
<=
BETWEEN
LIKE
IN
__________________________________
__________________________________
The AND operator displays a record if both the first condition AND the second condition are
true.
The OR operator displays a record if either the first condition OR the second condition is
true.
Command
Function
The ORDER BY keyword is used to sort the result-set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in a descending order, you can use the DESC keyword.
Command
function
SELECT *
ORDER BY
SELECT *
ORDER BY
FROM Customers
Country;
FROM Customers
Country DESC;
__________________________________
__________________________________
The first form does not specify the column names where the data will be inserted, only their
values:
Command
INSERT INTO Customers (CustomerName,
ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal','Tom B.
Erichsen','Skagen
21','Stavanger','4006','Norway');
INSERT INTO Customers (CustomerName,
City, Country)
VALUES ('Cardinal', 'Stavanger',
'Norway');
function
inserts a new row in the "Customers" table
Command
function
UPDATE Customers
SET ContactName='Alfred Schmidt',
City='Hamburg'
WHERE CustomerName='Alfreds
Futterkiste';
__________________________________
__________________________________
Command
function
It is possible to delete all rows in a table without deleting the table. This means that the
table structure, attributes, and indexes will be intact:
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause can be very useful on large tables with thousands of records.
Returning a large number of records can impact on performance.
Note: Not all database systems support the SELECT TOP clause.
MySQL Syntax
SELECT column_name(s)
FROM table_name
LIMIT number;
__________________________________
__________________________________
Example
SELECT *
FROM Persons
LIMIT 5;
Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example
SELECT *
FROM Persons
WHERE ROWNUM <=5;
Command
function
In SQL, wildcard characters are used with the SQL LIKE operator.SQL wildcards are used to
search for data within a table.
With SQL, the wildcards are:
Wildcard
Description
[charlist]
__________________________________
__________________________________
[^charlist]
or
[!charlist]
Command
Function
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Command
Function
The BETWEEN operator selects values within a range. The values can be numbers, text, or
dates.
ProductID ProductName
Price
18
Chais
__________________________________
10 boxes x 20 bags
__________________________________
Chang
24 - 12 oz bottles
19
Aniseed Syrup
12 - 550 ml bottles
10
48 - 6 oz jars
22
36 boxes
21.35
Example 1:
Command
function
Example 2:
OrderID
CustomerID
EmployeeID
OrderDate
ShipperID
10248
90
7/4/1996
10249
81
7/5/1996
10250
34
7/8/1996
10251
84
7/9/1996
10252
76
7/10/1996
Command
function
SQL aliases are used to give a database table or a column in a table, a temporary name.
Basically aliases are created to make column names more readable.
__________________________________
__________________________________
ContactName Address
City
PostalCode Country
Ana
Trujillo Ana Trujillo
Emparedados
y
helados
Avda. de la Mxico
Constitucin
D.F.
2222
05021
Mexico
Antonio
Taquera
Mataderos
2312
05023
Mexico
WA1 1DP
UK
Moreno Antonio
Moreno
Mxico
D.F.
Hanover London
CustomerID
EmployeeID
OrderDate
ShipperID
10354
58
1996-11-14
10355
1996-11-15
10356
86
1996-11-18
Command
function
specifies
two
aliases,
one
for
the
CustomerName column and one for the
ContactName column.
Tip: It require double quotation marks
or square brackets if the column name
contains spaces:
__________________________________
__________________________________
The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns in both tables.
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
PS! INNER JOIN is the same as JOIN.
Command
function
SELECT Customers.CustomerName,
Orders.OrderID
FROM Customers
INNER JOIN Orders
ON
Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are rows in the "Customers" table that do not have matches
in "Orders", these customers will NOT be listed.
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows
in the right table (table2). The result is NULL in the right side when there is no match.
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
__________________________________
__________________________________
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching
rows in the left table (table1). The result is NULL in the left side when there is no match.
JOIN table2
or:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
PS! In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the
right table (table2).
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of
columns. The columns must also have similar data types. Also, the columns in each SELECT
statement must be in the same order.
__________________________________
__________________________________
ALL
PS: The column names in the result-set of a UNION are usually equal to the column names
in the first SELECT statement in the UNION
Command
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
function
selects
all
the different cities
(only
distinct values) from the "Customers" and
the "Suppliers" tables
uses UNION ALL to select all (duplicate
values also) cities from the "Customers"
and "Suppliers" tables
uses UNION ALL to select all (duplicate
values also) German cities from the
"Customers" and "Suppliers" tables
The SELECT INTO statement selects data from one table and inserts it into a new table.
SELECT *
INTO newtable [IN externaldb]
FROM table1;
Or we can copy only the columns we want into the new table:
SELECT column_name(s)
INTO newtable [IN externaldb]
FROM table1;
__________________________________
__________________________________
Tip: The new table will be created with the column-names and types as defined
in the SELECT statement. You can apply new names using the AS clause.
Command
SELECT *
INTO CustomersBackup2013
FROM Customers;
SELECT *
INTO CustomersBackup2013 IN
'Backup.mdb'
FROM Customers;
SELECT CustomerName, ContactName
INTO CustomersBackup2013
FROM Customers;
SELECT *
INTO CustomersBackup2013
FROM Customers
WHERE Country='Germany;
SELECT Customers.CustomerName,
Orders.OrderID
INTO CustomersOrderBackup2013
FROM Customers
LEFT JOIN Orders
ON
Customers.CustomerID=Orders.CustomerID;
SELECT *
INTO newtable
FROM table1
WHERE 1=0;
function
Create a backup copy of Customers
Use the IN clause to copy the table into
another database
Copy only a few columns into the new
table
Copy only the German customers into the
new table
The INSERT INTO SELECT statement selects data from one table and inserts it into an
existing table. Any existing rows in the target table are unaffected.
__________________________________
__________________________________
Command
function
Copy
only
a
few
columns
"Suppliers" into "Customers"
from
table_name
data_type(size),
data_type(size),
data_type(size),
The column_name parameters specify the names of the columns of the table.
The data_type parameter specifies what type of data the column can hold (e.g. varchar,
integer, decimal, date, etc.).
The size parameter specifies the maximum length of the column of the table.
Tip: For an overview of the data types available in MS Access, MySQL, and SQL
Server, go to our complete Data Types Reference.
Command
INSERT INTO Customers (CustomerName,
Country)
SELECT SupplierName, Country FROM
Suppliers;
INSERT INTO Customers (CustomerName,
Country)
SELECT SupplierName, Country FROM
Suppliers
WHERE Country='Germany';
__________________________________
function
Copy
only
a
few
columns
"Suppliers" into "Customers"
from
__________________________________
SQL Dates
The most difficult part when working with dates is to be sure that the format of the
date you are trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected.
However, if a time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at the most
important built-in functions for working with dates.
The following table lists the most important built-in date functions in MySQL:
Function
Description
NOW()
CURDATE()
CURTIME()
DATE()
EXTRACT()
DATE_ADD()
DATE_SUB()
DATEDIFF()
DATE_FORMAT()
The following table lists the most important built-in date functions in SQL Server:
Function
Description
GETDATE()
DATEPART()
DATEADD()
DATEDIFF()
CONVERT()
__________________________________
__________________________________
MySQL comes with the following data types for storing a date or a date/time value in the
database:
SQL Server comes with the following data types for storing a date or a date/time value in
the database:
Note: The date types are chosen for a column when you create a new table in your
database!
Data type
Description
Storage
Text
Memo
Byte
1 byte
Integer
2 bytes
Long
Allows
whole
2,147,483,647
Single
4 bytes
Double
8 bytes
Currency
AutoNumber
Date/Time
numbers
__________________________________
between
-2,147,483,648
and 4 bytes
8 bytes
__________________________________
Yes/No
Ole Object
Can store pictures, audio, video, or other BLOBs (Binary Large up to 1GB
OBjects)
Hyperlink
Lookup Wizard
Let you type a list of options, which can then be chosen from a 4 bytes
drop-down list
In MySQL there are three main types : text, number, and Date/Time types.
Text types:
Data type
Description
CHAR(size)
Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255
characters
VARCHAR(size)
Holds a variable length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255
characters. Note: If you put a greater value than 255 it will be converted to a
TEXT type
TINYTEXT
TEXT
BLOB
MEDIUMTEXT
MEDIUMBLOB
LONGTEXT
LONGBLOB
ENUM(x,y,z,etc.)
Let you enter a list of possible values. You can list up to 65535 values in an
ENUM list. If a value is inserted that is not in the list, a blank value will be
inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
SET
Similar to ENUM except that SET may contain up to 64 list items and can store
more than one choice
__________________________________
__________________________________
Number types:
Data type
Description
TINYINT(size)
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may
be specified in parenthesis
SMALLINT(size)
BIGINT(size)
-9223372036854775808
to
9223372036854775807
normal.
0
to
18446744073709551615 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
FLOAT(size,d)
A small number with a floating decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter
DOUBLE(size,d)
A large number with a floating decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter
DECIMAL(size,d)
A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number
of digits to the right of the decimal point is specified in the d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from
an negative to positive value. Adding the UNSIGNED attribute will move that range up so it
starts at zero instead of a negative number.
__________________________________
__________________________________
Date types:
Data type
Description
DATE()
DATETIME()
TIMESTAMP()
TIME()
YEAR()
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In
an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date
and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS,
YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.
__________________________________
__________________________________
String types:
Data type
Description
Storage
char(n)
Fixed width
characters
varchar(n)
Variable width
characters
varchar(max)
Variable
width
character
1,073,741,824 characters
Text
Nchar
Fixed width
characters
Nvarchar
Variable width
characters
nvarchar(max)
Ntext
Bit
Allows 0, 1, or NULL
binary(n)
Varbinary
varbinary(max)
Image
character
character
Unicode
Unicode
__________________________________
string.
string.
string.
string.
Maximum
Maximum
string.
Maximum
Maximum
4,000
__________________________________
Number types:
Data type
Description
Storage
Tinyint
1 byte
Smallint
2 bytes
Int
Allows
whole
2,147,483,647
Bigint
decimal(p,s)
numbers
between
-2,147,483,648
and 4 bytes
5-17 bytes
5-17 bytes
Money
Monetary
data
from
922,337,203,685,477.5807
float(n)
-922,337,203,685,477.5808
4 bytes
to 8 bytes
__________________________________
__________________________________
Date types:
Data type
Description
Storage
Datetime
datetime2
From January 1, 0001 to December 31, 9999 with an accuracy 6-8 bytes
of 100 nanoseconds
smalldatetime
Date
3 bytes
Time
3-5 bytes
datetimeoffset
8-10 bytes
Timestamp
Description
sql_variant
Stores up to 8,000 bytes of data of various data types, except text, ntext,
and timestamp
uniqueidentifier
Xml
Cursor
Table
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
__________________________________
__________________________________
SQL scalar functions return a single value, based on the input value.
Useful scalar functions:
Tip: The aggregate functions and the scalar functions will be explained in details in the next
chapters.
Command
function
__________________________________
__________________________________
The FIRST() function returns the first value of the selected column.
Example
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID ASC;
MySQL Syntax
SELECT column_name FROM table_name
ORDER BY column_name ASC
LIMIT 1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID ASC
LIMIT 1;
Oracle Syntax
SELECT column_name FROM table_name
ORDER BY column_name ASC
WHERE ROWNUM <=1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID ASC
WHERE ROWNUM <=1;
__________________________________
__________________________________
The LAST() function returns the last value of the selected column.
Example
SELECT TOP 1 CustomerName FROM Customers
ORDER BY CustomerID DESC;
MySQL Syntax
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID DESC
LIMIT 1;
Oracle Syntax
SELECT column_name FROM table_name
ORDER BY column_name DESC
WHERE ROWNUM <=1;
Example
SELECT CustomerName FROM Customers
ORDER BY CustomerID DESC
WHERE ROWNUM <=1;
The MAX() function returns the largest value of the selected column.
__________________________________
__________________________________
The MIN() function returns the smallest value of the selected column.
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
Command
SELECT Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees
ON
Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
SELECT Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees
ON
Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR
LastName='Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
__________________________________
function
has
__________________________________
The following SQL statement selects the first four characters from the "City" column from
the "Customers" table:
Example
SELECT MID(City,1,4) AS ShortCity
FROM Customers;
The LEN() function returns the length of the value in a text field.
__________________________________
__________________________________
The ROUND() function is used to round a numeric field to the number of decimals specified.
The NOW() function returns the current system date and time.
Source : http://www.w3schools.com/sql/
__________________________________
__________________________________