SQL W3schools
SQL W3schools
SQL W3schools
in
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard
RDBMS
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.
Created By www.ebooktutorials.blogspot.in
SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example ofa table called "Persons": P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger The table above contains three records (one for each person) and five columns (P_Id, LastName, FirstName, Address, and City).
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements. The following SQL statement will select all the records in the "Persons" table: SELECT * FROM Persons In this tutorial we will teach you all about the different SQL statements.
Created By www.ebooktutorials.blogspot.in
SELECT * Example
Now we want to select all the columns from the "Persons" table. We use the following SELECT statement: SELECT * FROM Persons Tip: The asterisk (*) is a quick way of selecting all columns! The result-set will look like this: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
Navigation in a Result-set
Most database software systems allow navigation in the result-set with programming functions, like: Move-To-First-Record, Get-RecordContent, Move-To-Next-Record, etc.
Created By www.ebooktutorials.blogspot.in
Created By www.ebooktutorials.blogspot.in
Created By www.ebooktutorials.blogspot.in
Note: In some versions of SQL the <> operator may be written as !=
Created By www.ebooktutorials.blogspot.in
OR Operator Example
Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to "Ola": We use the following SELECT statement: SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola' The result-set will look like this: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes
Created By www.ebooktutorials.blogspot.in
ORDER BY Example
The "Persons" table: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger 4 Nilsen Tom Vingvn 23 Stavanger Now we want to select all the persons from the table above, however, we want to sort the persons by their last name. We use the following SELECT statement: SELECT * FROM Persons ORDER BY LastName The result-set will look like this: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 4 Nilsen Tom Vingvn 23 Stavanger 3 Pettersen Kari Storgt 20 Stavanger 2 Svendson Tove Borgvn 23 Sandnes
Created By www.ebooktutorials.blogspot.in
Created By www.ebooktutorials.blogspot.in
10
Created By www.ebooktutorials.blogspot.in
11
Created By www.ebooktutorials.blogspot.in
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
12
Created By www.ebooktutorials.blogspot.in
We use the following SELECT statement: SELECT TOP 50 PERCENT * FROM Persons The result-set will look like this: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes
13
Created By www.ebooktutorials.blogspot.in
14
Created By www.ebooktutorials.blogspot.in
SQL Wildcards
SQL wildcards can be used when searching for data in a database.
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database. SQL wildcards must be used with the SQL LIKE operator. With SQL, the following wildcards can be used: Wildcard % _ [charlist] [^charlist] or [!charlist] Description A substitute for zero or more characters A substitute for exactly one character Any single character in charlist Any single character not in charlist
15
Created By www.ebooktutorials.blogspot.in
We use the following SELECT statement: SELECT * FROM Persons WHERE LastName LIKE 'S_end_on' The result-set will look like this: P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Sandnes
16
Created By www.ebooktutorials.blogspot.in
SQL IN Operator
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...)
IN Operator Example
The "Persons" table: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the table above. We use the following SELECT statement: SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen') The result-set will look like this: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
17
Created By www.ebooktutorials.blogspot.in
Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN: SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen' The result-set will look like this: P_Id LastName FirstName Address City 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger
18
Created By www.ebooktutorials.blogspot.in
SQL Alias
With SQL, an alias name can be given to a table or to a column.
SQL Alias
You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names. An alias name could be anything, but usually it is short.
Alias Example
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the table aliases of "p" and "po" respectively. Now we want to list all the orders that "Ola Hansen" is responsible for. We use the following SELECT statement: SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p, Product_Orders AS po WHERE p.LastName='Hansen' AND p.FirstName='Ola' The same SELECT statement without aliases: SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons, Product_Orders WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola' As you'll see from the two SELECT statements above; aliases can make queries easier both to write and to read.
19
Created By www.ebooktutorials.blogspot.in
SQL Joins
SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.
SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables. Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table. Look at the "Persons" table: P_Id LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name. Next, we have the "Orders" table: O_Id 1 2 3 4 5 OrderNo 77895 44678 22456 24562 34764 P_Id 3 3 1 1 15
Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to the persons in the "Persons" table without using their names. Notice that the relationship between the two tables above is the "P_Id" column.
20
Created By www.ebooktutorials.blogspot.in
Now we want to list all the persons with any orders. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 Pettersen Kari 44678 The INNER JOIN keyword returns rows when there is at least one match in both tables. If there are rows in "Persons" that do not have matches in "Orders", those rows will NOT be listed.
21
Created By www.ebooktutorials.blogspot.in
Now we want to list all the persons and their orders - if any, from the tables above. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 Pettersen Kari 44678 Svendson Tove The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in the right table (Orders).
22
Created By www.ebooktutorials.blogspot.in
Now we want to list all the orders with containing persons - if any, from the tables above. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 Pettersen Kari 44678 34764 The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches in the left table (Persons).
23
Created By www.ebooktutorials.blogspot.in
Now we want to list all the persons and their orders, and all the orders with their persons. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: LastName FirstName OrderNo Hansen Ola 22456 Hansen Ola 24562 Pettersen Kari 77895 Pettersen Kari 44678 Svendson Tove 34764 The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Persons", those rows will be listed as well.
24
Created By www.ebooktutorials.blogspot.in
Now we want to list all the different employees in Norway and USA. We use the following SELECT statement: SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA The result-set will look like this: E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Scott, Stephen Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.
25
Created By www.ebooktutorials.blogspot.in
E_Name Hansen, Ola Svendson, Tove Svendson, Stephen Pettersen, Kari Turner, Sally Kent, Clark Svendson, Stephen Scott, Stephen
26
Created By www.ebooktutorials.blogspot.in
27
Created By www.ebooktutorials.blogspot.in
28
Created By www.ebooktutorials.blogspot.in
The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.
29
Created By www.ebooktutorials.blogspot.in
SQL Constraints
SQL Constraints
Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement). We will focus on the following constraints: NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT The next chapters will describe each constraint in detail.
30
Created By www.ebooktutorials.blogspot.in
31
Created By www.ebooktutorials.blogspot.in
32
Created By www.ebooktutorials.blogspot.in
33
Created By www.ebooktutorials.blogspot.in
DROP PRIMARY KEY SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT pk_PersonID
34
Created By www.ebooktutorials.blogspot.in
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.
35
Created By www.ebooktutorials.blogspot.in
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
36
Created By www.ebooktutorials.blogspot.in
37
Created By www.ebooktutorials.blogspot.in
38
Created By www.ebooktutorials.blogspot.in
Indexes
An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
39
Created By www.ebooktutorials.blogspot.in
40
Created By www.ebooktutorials.blogspot.in
41
Created By www.ebooktutorials.blogspot.in
1 2 3 Hansen Svendson Pettersen Ola Tove Kari Timoteivn 10 Sandnes Borgvn 23 Sandnes Storgt 20 Stavanger
42
Created By www.ebooktutorials.blogspot.in
43
Created By www.ebooktutorials.blogspot.in
The MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new record. To specify that the "P_Id" column should start at value 10 and increment by 5, change the autoincrement to AUTOINCREMENT(10,5). To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically): INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen') The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
44
Created By www.ebooktutorials.blogspot.in
SQL Views
A view is a virtual table. This chapter shows how to create, update, and delete a view.
45
Created By www.ebooktutorials.blogspot.in
SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No
46
Created By www.ebooktutorials.blogspot.in
SQL IS NULL
How do we select only the records with NULL values in the "Address" column? We will have to use the IS NULL operator: SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NULL The result-set will look like this: LastName FirstName Address Hansen Ola Pettersen Kari Tip: Always use IS NULL to look for NULL values.
47
Created By www.ebooktutorials.blogspot.in
48
Created By www.ebooktutorials.blogspot.in
*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:
49
Created By www.ebooktutorials.blogspot.in
Data type DATE() DATETIME() TIMESTAMP() Description A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31' *A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59' *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59' A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069 *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.
TIME() YEAR()
numeric(p,s)
50
Created By www.ebooktutorials.blogspot.in
real Date types: Data type datetime datetime2 smalldatetime date time datetimeoffset timestamp Description From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute Store a date only. From January 1, 0001 to December 31, 9999 Store a time only to an accuracy of 100 nanoseconds The same as datetime2 with the addition of a time zone offset Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable Storage 8 bytes 6-8 bytes 4 bytes 3 bytes 3-5 bytes 8-10 bytes Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes
Other data types: Data type sql_variant uniqueidentifier xml cursor table Description Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp Stores a globally unique identifier (GUID) Stores XML formatted data. Maximum 2GB Stores a reference to a cursor used for database operations Stores a result-set for later processing
51
Created By www.ebooktutorials.blogspot.in
Now we want to select the records with an OrderDate of "2008-11-11" from the table above. We use the following SELECT statement:
52
Created By www.ebooktutorials.blogspot.in
SELECT * FROM Orders WHERE OrderDate='2008-11-11' The result-set will look like this: OrderId ProductName 1 Geitost Mozzarella di 3 Giovanni OrderDate 2008-11-11 2008-11-11
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate" column): OrderId 1 2 3 4 ProductName Geitost Camembert Pierrot Mozzarella di Giovanni Mascarpone Fabioli OrderDate 2008-11-11 13:23:44 2008-11-09 15:45:21 2008-11-11 11:12:01 2008-10-29 14:56:59
If we use the same SELECT statement as above: SELECT * FROM Orders WHERE OrderDate='2008-11-11' we will get no result! This is because the query is looking only for dates with no time portion. Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your dates!
53
Created By www.ebooktutorials.blogspot.in
Syntax
NOW()
Example
The following SELECT statement: SELECT NOW(),CURDATE(),CURTIME() will result in something like this: NOW() CURDATE() 2008-11-11 12:45:34 2008-11-11 CURTIME() 12:45:34
Example
The following SQL creates an "Orders" table with a datetime column (OrderDate): CREATE TABLE Orders ( OrderId int NOT NULL, ProductName varchar(50) NOT NULL, OrderDate datetime NOT NULL DEFAULT NOW(), PRIMARY KEY (OrderId) ) Notice that the OrderDate column specifies NOW() as the default value. As a result, when you insert a row into the table, the current date and time are automatically inserted into the column. Now we want to insert a record into the "Orders" table: INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese') The "Orders" table will now look something like this: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657
54
Created By www.ebooktutorials.blogspot.in
Syntax
CURDATE()
Example
The following SELECT statement: SELECT NOW(),CURDATE(),CURTIME() will result in something like this: NOW() CURDATE() 2008-11-11 12:45:34 2008-11-11 CURTIME() 12:45:34
Example
The following SQL creates an "Orders" table with a datetime column (OrderDate): CREATE TABLE Orders ( OrderId int NOT NULL, ProductName varchar(50) NOT NULL, OrderDate datetime NOT NULL DEFAULT CURDATE(), PRIMARY KEY (OrderId) ) Notice that the OrderDate column specifies CURDATE() as the default value. As a result, when you insert a row into the table, the current date are automatically inserted into the column. Now we want to insert a record into the "Orders" table: INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese') The "Orders" table will now look something like this: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11
55
Created By www.ebooktutorials.blogspot.in
Syntax
CURTIME()
Example
The following SELECT statement: SELECT NOW(),CURDATE(),CURTIME() will result in something like this: NOW() CURDATE() 2008-11-11 12:45:34 2008-11-11 CURTIME() 12:45:34
56
Created By www.ebooktutorials.blogspot.in
Syntax
DATE(date) Where date is a valid date expression.
Example
Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657 The following SELECT statement: SELECT ProductName, DATE(OrderDate) AS OrderDate FROM Orders WHERE OrderId=1 will result in this: ProductName Jarlsberg Cheese OrderDate 2008-11-11
57
Created By www.ebooktutorials.blogspot.in
Syntax
EXTRACT(unit FROM date) Where date is a valid date expression and unit can be one of the following: Unit Value MICROSECOND SECOND MINUTE HOUR DAY WEEK MONTH QUARTER YEAR SECOND_MICROSECOND MINUTE_MICROSECOND MINUTE_SECOND HOUR_MICROSECOND HOUR_SECOND HOUR_MINUTE DAY_MICROSECOND DAY_SECOND DAY_MINUTE DAY_HOUR YEAR_MONTH
Example
Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657 The following SELECT statement: SELECT EXTRACT(YEAR FROM OrderDate) AS OrderYear, EXTRACT(MONTH FROM OrderDate) AS OrderMonth, EXTRACT(DAY FROM OrderDate) AS OrderDay, FROM Orders WHERE OrderId=1 will result in this: OrderYear 2008 OrderMonth 11 OrderDay 11
58
Created By www.ebooktutorials.blogspot.in
Syntax
DATE_ADD(date,INTERVAL expr type) Where date is a valid date expression and expr is the number of interval you want to add. type can be one of the following: Type Value MICROSECOND SECOND MINUTE HOUR DAY WEEK MONTH QUARTER YEAR SECOND_MICROSECOND MINUTE_MICROSECOND MINUTE_SECOND HOUR_MICROSECOND HOUR_SECOND HOUR_MINUTE DAY_MICROSECOND DAY_SECOND DAY_MINUTE DAY_HOUR YEAR_MONTH
Example
Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657 Now we want to add 45 days to the "OrderDate", to find the payment date. We use the following SELECT statement: SELECT OrderId,DATE_ADD(OrderDate,INTERVAL 45 DAY) AS OrderPayDate FROM Orders Result: OrderId OrderPayDate 1 2008-12-26 13:23:44.657
59
Created By www.ebooktutorials.blogspot.in
Syntax
DATE_SUB(date,INTERVAL expr type) Where date is a valid date expression and expr is the number of interval you want to subtract. type can be one of the following: Type Value MICROSECOND SECOND MINUTE HOUR DAY WEEK MONTH QUARTER YEAR SECOND_MICROSECOND MINUTE_MICROSECOND MINUTE_SECOND HOUR_MICROSECOND HOUR_SECOND HOUR_MINUTE DAY_MICROSECOND DAY_SECOND DAY_MINUTE DAY_HOUR YEAR_MONTH
Example
Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657 Now we want to subtract 5 days from the "OrderDate" date. We use the following SELECT statement: SELECT OrderId,DATE_SUB(OrderDate,INTERVAL 5 DAY) AS SubtractDate FROM Orders Result: OrderId 1 SubtractDate 2008-11-06 13:23:44.657
60
Created By www.ebooktutorials.blogspot.in
Syntax
DATEDIFF(date1,date2) Where date1 and date2 are valid date or date/time expressions. Note: Only the date parts of the values are used in the calculation.
Example
The following SELECT statement: SELECT DATEDIFF('2008-11-30','2008-11-29') AS DiffDate will result in this: DiffDate 1
Example
The following SELECT statement: SELECT DATEDIFF('2008-11-29','2008-11-30') AS DiffDate will result in this: DiffDate -1
61
Created By www.ebooktutorials.blogspot.in
Syntax
DATE_FORMAT(date,format) Where date is a valid date and format specifies the output format for the date/time. The formats that can be used are: Format %a %b %c %D %d %e %f %H %h %I %i %j %k %l %M %m %p %r %S %s %T %U %u %V %v %W %w %X %x %Y %y Description Abbreviated weekday name Abbreviated month name Month, numeric Day of month with English suffix Day of month, numeric (00-31) Day of month, numeric (0-31) Microseconds Hour (00-23) Hour (01-12) Hour (01-12) Minutes, numeric (00-59) Day of year (001-366) Hour (0-23) Hour (1-12) Month name Month, numeric (00-12) AM or PM Time, 12-hour (hh:mm:ss AM or PM) Seconds (00-59) Seconds (00-59) Time, 24-hour (hh:mm:ss) Week (00-53) where Sunday is the first day of week Week (00-53) where Monday is the first day of week Week (01-53) where Sunday is the first day of week, used with %X Week (01-53) where Monday is the first day of week, used with %x Weekday name Day of the week (0=Sunday, 6=Saturday) Year of the week where Sunday is the first day of week, four digits, used with %V Year of the week where Monday is the first day of week, four digits, used with %v Year, four digits Year, two digits
Example
The following script uses the DATE_FORMAT() function to display different formats. We will use the NOW() function to get the current date/time: DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p') DATE_FORMAT(NOW(),'%m-%d-%Y') DATE_FORMAT(NOW(),'%d %b %y') DATE_FORMAT(NOW(),'%d %b %Y %T:%f') The result would look something like this: Nov 04 2008 11:45 PM 11-04-2008 04 Nov 08 04 Nov 2008 11:45:34:243
62
Created By www.ebooktutorials.blogspot.in
Syntax
GETDATE()
Example
The following SELECT statement: SELECT GETDATE() AS CurrentDateTime will result in something like this: CurrentDateTime 2008-11-11 12:45:34.243 Note: The time part above goes all the way to milliseconds.
Example
The following SQL creates an "Orders" table with a datetime column (OrderDate): CREATE TABLE Orders ( OrderId int NOT NULL PRIMARY KEY, ProductName varchar(50) NOT NULL, OrderDate datetime NOT NULL DEFAULT GETDATE() ) Notice that the OrderDate column specifies GETDATE() as the default value. As a result, when you insert a row into the table, the current date and time are automatically inserted into the column. Now we want to insert a record into the "Orders" table: INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese') The "Orders" table will now look something like this: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657
63
Created By www.ebooktutorials.blogspot.in
Syntax
DATEPART(datepart,date) Where date is a valid date expression and datepart can be one of the following: datepart Abbreviation year yy, yyyy quarter qq, q month mm, m dayofyear dy, y day dd, d week wk, ww weekday dw, w hour hh minute mi, n second ss, s millisecond ms microsecond mcs nanosecond ns
Example
Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657 The following SELECT statement: SELECT DATEPART(yyyy,OrderDate) AS OrderYear, DATEPART(mm,OrderDate) AS OrderMonth, DATEPART(dd,OrderDate) AS OrderDay, FROM Orders WHERE OrderId=1 will result in this: OrderYear 2008 OrderMonth 11 OrderDay 11
64
Created By www.ebooktutorials.blogspot.in
Syntax
DATEADD(datepart,number,date) Where date is a valid date expression and number is the number of interval you want to add. The number can either be positive, for dates in the future, or negative, for dates in the past. datepart can be one of the following: datepart Abbreviation year yy, yyyy quarter qq, q month mm, m dayofyear dy, y day dd, d week wk, ww weekday dw, w hour hh minute mi, n second ss, s millisecond ms microsecond mcs nanosecond ns
Example
Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 Jarlsberg Cheese 2008-11-11 13:23:44.657 Now we want to add 45 days to the "OrderDate", to find the payment date. We use the following SELECT statement: SELECT OrderId,DATEADD(day,45,OrderDate) AS OrderPayDate FROM Orders Result: OrderId 1 OrderPayDate 2008-12-26 13:23:44.657
65
Created By www.ebooktutorials.blogspot.in
Syntax
DATEDIFF(datepart,startdate,enddate) Where startdate and enddate are valid date expressions and datepart can be one of the following: datepart Abbreviation year yy, yyyy quarter qq, q month mm, m dayofyear dy, y day dd, d week wk, ww weekday dw, w hour hh minute mi, n second ss, s millisecond ms microsecond mcs nanosecond ns
Example
Now we want to get the number of days between two dates. We use the following SELECT statement: SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate Result: DiffDate 61
Example
Now we want to get the number of days between two dates (notice that the second date is "earlier" than the first date, and will result in a negative number). We use the following SELECT statement: SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDate Result: DiffDate -61
66
Created By www.ebooktutorials.blogspot.in
Syntax
CONVERT(data_type(length),expression,style ) Value Description Specifies the target data type (with an optional length) Specifies the value to be converted Specifies the output format for the date/time
The table below represent the style values for datetime or smalldatetime conversion to character data: Value Value Input/Output (century yy) (century yyyy) 0 or 100 mon dd yyyy hh:miAM (or PM) 1 101 mm/dd/yy 2 102 yy.mm.dd 3 103 dd/mm/yy 4 104 dd.mm.yy 5 105 dd-mm-yy 6 106 dd mon yy 7 107 Mon dd, yy 8 108 hh:mm:ss 9 or 109 mon dd yyyy hh:mi:ss:mmmAM (or PM) 10 110 mm-dd-yy 11 111 yy/mm/dd 12 112 yymmdd 13 or 113 dd mon yyyy hh:mi:ss:mmm (24h) 14 114 hh:mi:ss:mmm (24h) 20 or 120 yyyy-mm-dd hh:mi:ss (24h) yyyy-mm-dd hh:mi:ss.mmm (24h) 21 or 121 126 yyyy-mm-ddThh:mi:ss.mmm (no spaces) 130 dd mon yyyy hh:mi:ss:mmmAM 131 dd/mm/yy hh:mi:ss:mmmAM Standard Default USA ANSI British/French German Italian Default+millisec USA Japan ISO ISO8601 Hijiri Hijiri
Example
The following script uses the CONVERT() function to display different formats. We will use the GETDATE() function to get the current date/time: CONVERT(VARCHAR(19),GETDATE()) CONVERT(VARCHAR(10),GETDATE(),10) CONVERT(VARCHAR(10),GETDATE(),110) CONVERT(VARCHAR(11),GETDATE(),6) CONVERT(VARCHAR(11),GETDATE(),106) CONVERT(VARCHAR(24),GETDATE(),113) The result would look something like this: Nov 04 2011 11:45 PM 11-04-11 11-04-2011 04 Nov 11 04 Nov 2011 04 Nov 2011 11:45:34:243
67
Created By www.ebooktutorials.blogspot.in
SQL Functions
SQL has many built-in functions for performing calculations on data.
68
Created By www.ebooktutorials.blogspot.in
69
Created By www.ebooktutorials.blogspot.in
70
Created By www.ebooktutorials.blogspot.in
71
Created By www.ebooktutorials.blogspot.in
72
Created By www.ebooktutorials.blogspot.in
73
Created By www.ebooktutorials.blogspot.in
74
Created By www.ebooktutorials.blogspot.in
75
Created By www.ebooktutorials.blogspot.in
The result-set above is not what we wanted. Explanation of why the above SELECT statement cannot be used: The SELECT statement above has two columns specified (Customer and SUM(OrderPrice). The "SUM(OrderPrice)" returns a single value (that is the total sum of the "OrderPrice" column), while "Customer" returns 6 values (one value for each row in the "Orders" table). This will therefore not give us the correct result. However, you have seen that the GROUP BY statement solves this problem.
76
Created By www.ebooktutorials.blogspot.in
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500. We add an ordinary WHERE clause to the SQL statement: SELECT Customer,SUM(OrderPrice) FROM Orders WHERE Customer='Hansen' OR Customer='Jensen' GROUP BY Customer HAVING SUM(OrderPrice)>1500 The result-set will look like this: Customer Hansen Jensen SUM(OrderPrice) 2000 2000
77
Created By www.ebooktutorials.blogspot.in
78
Created By www.ebooktutorials.blogspot.in
79
Created By www.ebooktutorials.blogspot.in
80
Created By www.ebooktutorials.blogspot.in
81
Created By www.ebooktutorials.blogspot.in
82
Created By www.ebooktutorials.blogspot.in
83
Created By www.ebooktutorials.blogspot.in
84
Created By www.ebooktutorials.blogspot.in
ALTER TABLE
AS (alias)
BETWEEN
CREATE INDEX
CREATE VIEW
DELETE
HAVING
IN
INSERT INTO
or
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,....) SELECT column_name(s) FROM table_name1 INNER JOIN table_name2
INNER JOIN
85
Created By www.ebooktutorials.blogspot.in
LEFT JOIN ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern SELECT column_name(s) FROM table_name ORDER BY column_name [ASC|DESC] SELECT column_name(s) FROM table_name SELECT * FROM table_name SELECT DISTINCT column_name(s) FROM table_name SELECT * INTO new_table_name [IN externaldatabase] FROM old_table_name
RIGHT JOIN
FULL JOIN
or
SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_table_name SELECT TOP number|percent column_name(s) FROM table_name TRUNCATE TABLE table_name SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 UPDATE table_name SET column1=value, column2=value,... WHERE some_column=some_value SELECT column_name(s) FROM table_name WHERE column_name operator value
Source : http://www.w3schools.com/sql/sql_quickref.asp
86
Created By www.ebooktutorials.blogspot.in
SQL Hosting
SQL Hosting
If you want your web site to be able to store and display data from a database, your web server should have access to a database system that uses the SQL language. If your web server will be hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting plans. The most common SQL hosting databases are MySQL, MS SQL Server, and MS Access. You can have SQL databases on both Windows and Linux/UNIX operating systems. Below is an overview of which database system that runs on which OS. MS SQL Server Runs only on Windows OS. MySQL Runs on Windows, Mac OS X, and Linux/UNIX operating systems. MS Access (recommended only for small websites) Runs only on Windows OS.
87