Date post: | 06-Jan-2016 |
Category: |
Documents |
Upload: | golf-romeo |
View: | 9 times |
Download: | 0 times |
of 46
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
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
SQL is a Standard - BUT....
Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language.
However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.
Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
Using SQL in Your Web Site
To build a web site that shows some data from a database, you will need the following:
An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
A server-side scripting language, like PHP or ASP
SQL
HTML / CSS
Relational Database Management System
RDBMS is the basis for SQL, and for all modern database systems like 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 collections of related data entries and it consists of columns and rows.
Below is an example ofa table called "Persons":
P_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
The "Persons" table contains three rows (one for each person) and five columns (P_Id, LastName, FirstName, Address, and City).
Another example is a table called "Orders":
O_IdOrderNoP_Id
1778953
2446783
3224561
4245621
The "Orders" table contains five rows (one for each order) and three columns (O_Id, OrderNo, P_Id).
Notice that the relationship between the two tables above is the "P_Id" column (which refers to the persons in the "Persons" table without using their names).
The data in RDBMS is stored into group of tables, which might or might not be related.
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_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
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.
Keep in Mind That...
SQL is not case sensitive
Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.
SQL DML and DLL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).
The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are:
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX- deletes an index
The SQL SELECT Statement
The SELECT statement is used to select data from a table.
The result is stored in a result table, called the result-set.
SQL SELECT SyntaxSELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
Note: SQL is not case sensitive. SELECT is the same as select.
An SQL SELECT Example
The "Persons" table:
P_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
Now we want to select the content of the columns named "LastName" and "FirstName" from the table above.
We use the following SELECT statement:
SELECT LastName,FirstName FROM Persons
The result-set will look like this:
LastNameFirstName
HansenOla
SvendsonTove
PettersenKari
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_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
Navigation in a Result-set
Most database software systems allow navigation in the result-set with programming functions, like: Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.
Programming functions like these are not a part of this tutorial. To learn about accessing data with function calls, please visit our ADO tutorial or our PHP tutorial.
The SQL SELECT DISTINCT Statement
In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT SyntaxSELECT DISTINCT column_name(s)
FROM table_name
SELECT DISTINCT Example
The "Persons" table:
P_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
Now we want to select only the distinct values from the column named "City" from the table above.
We use the following SELECT statement:
SELECT DISTINCT City FROM Persons
The result-set will look like this:
City
Sandnes
Stavanger
The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE SyntaxSELECT column_name(s)
FROM table_name
WHERE column_name operator value
WHERE Clause Example
The "Persons" table:
P_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
Now we want to select only the persons living in the city "Sandnes" from the table above.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'
The result-set will look like this:
P_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
Quotes Around Text Fields
SQL uses single quotes around text values (most database systems will also accept double quotes).
Although, numeric values should not be enclosed in quotes.
For text values:
This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove
For numeric values:
This is correct:
SELECT * FROM Persons WHERE Year=1965
This is wrong:
SELECT * FROM Persons WHERE Year='1965'
Operators Allowed in the WHERE Clause
With the WHERE clause, the following operators can be used:
OperatorDescription
=Equal
Not equal
>Greater than
=Greater than or equal
10000
Returns this result
CompanySUM(Amount)
W3Schools12600
The SELECT INTO Statement
The SELECT INTO statement is most often used to create backup copies of tables or for archiving records.
SyntaxSELECT column_name(s) INTO newtable [IN externaldatabase]
FROM source
Make a Backup Copy
The following example makes a backup copy of the "Persons" table:
SELECT * INTO Persons_backup
FROM Persons
The IN clause can be used to copy tables into another database:
SELECT Persons.* INTO Persons IN 'Backup.mdb'
FROM Persons
If you only want to copy a few fields, you can do so by listing them after the SELECT statement:
SELECT LastName,FirstName INTO Persons_backup
FROM Persons
You can also add a WHERE clause. The following example creates a "Persons_backup" table with two columns (FirstName and LastName) by extracting the persons who lives in "Sandnes" from the "Persons" table:
SELECT LastName,Firstname INTO Persons_backup
FROM Persons
WHERE City='Sandnes'
Selecting data from more than one table is also possible. The following example creates a new table "Empl_Ord_backup" that contains data from the two tables Employees and Orders:
SELECT Employees.Name,Orders.Product
INTO Empl_Ord_backup
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
A view is a virtual table based on the result-set of a SELECT statement.
What is a View?
In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from a single table.
Note: The database design and structure will NOT be affected by the functions, where, or join statements in a view.
SyntaxCREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: The database does not store the view data! The database engine recreates the data, using the view's SELECT statement, every time a user queries a view.
Using Views
A view could be used from inside a query, a stored procedure, or from inside another view. By adding functions, joins, etc., to a view, it allows you to present exactly the data you want to the user.
The sample database Northwind has some views installed by default. The view "Current Product List" lists all active products (products that are not discontinued) from the Products table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
We can query the view above as follows:
SELECT * FROM [Current Product List]
Another view from the Northwind sample database selects every product in the Products table that has a unit price that is higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows:
SELECT * FROM [Products Above Average Price]
Another example view from the Northwind database calculates the total sale for each category in 1997. Note that this view selects its data from another view called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997]
We can also add a condition to the query. Now we want to see the total sale only for the category "Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
Data types and ranges for Microsoft Access, MySQL and SQL Server.
Microsoft Access Data Types
Data typeDescriptionStorage
TextUse for text or combinations of text and numbers. 255 characters maximum
MemoMemo is used for larger amounts of text. Stores up to 65,536 characters. Note: You cannot sort a memo field. However, they are searchable
ByteAllows whole numbers from 0 to 2551 byte
IntegerAllows whole numbers between -32,768 and 32,7672 bytes
LongAllows whole numbers between -2,147,483,648 and 2,147,483,6474 bytes
SingleSingle precision floating-point. Will handle most decimals 4 bytes
DoubleDouble precision floating-point. Will handle most decimals8 bytes
CurrencyUse for currency. Holds up to 15 digits of whole dollars, plus 4 decimal places. Tip: You can choose which country's currency to use8 bytes
AutoNumberAutoNumber fields automatically give each record its own number, usually starting at 14 bytes
Date/TimeUse for dates and times8 bytes
Yes/NoA logical field can be displayed as Yes/No, True/False, or On/Off. In code, use the constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in Yes/No fields1 bit
Ole ObjectCan store pictures, audio, video, or other BLOBs (Binary Large OBjects)up to 1GB
HyperlinkContain links to other files, including web pages
Lookup WizardLet you type a list of options, which can then be chosen from a drop-down list4 bytes
MySQL Data Types
In MySQL there are three main types : text, number, and Date/Time types.
Text types:Data typeDescription
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
TINYTEXTHolds a string with a maximum length of 255 characters
TEXTHolds a string with a maximum length of 65,535 characters
BLOBFor BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXTHolds a string with a maximum length of 16,777,215 characters
MEDIUMBLOBFor BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXTHolds a string with a maximum length of 4,294,967,295 characters
LONGBLOBFor BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
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')
SETSimilar to ENUM except that SET may contain up to 64 list items and can store more than one choice
Number types:Data typeDescription
TINYINT(size)-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis
SMALLINT(size)-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis
MEDIUMINT(size)-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis
INT(size)-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis
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 typeDescription
DATE()A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME()*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'
TIMESTAMP()*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
TIME()A time. Format: HH:MM:SS
Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR()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.
SQL Server Data Types
Character strings:Data typeDescriptionStorage
char(n)Fixed-length character string. Maximum 8,000 charactersn
varchar(n)Variable-length character string. Maximum 8,000 characters
varchar(max)Variable-length character string. Maximum 1,073,741,824 characters
textVariable-length character string. Maximum 2GB of text data
Unicode strings:Data typeDescriptionStorage
nchar(n)Fixed-length Unicode data. Maximum 4,000 characters
nvarchar(n)Variable-length Unicode data. Maximum 4,000 characters
nvarchar(max)Variable-length Unicode data. Maximum 536,870,912 characters
ntextVariable-length Unicode data. Maximum 2GB of text data
Binary types:Data typeDescriptionStorage
bitAllows 0, 1, or NULL
binary(n)Fixed-length binary data. Maximum 8,000 bytes
varbinary(n)Variable-length binary data. Maximum 8,000 bytes
varbinary(max)Variable-length binary data. Maximum 2GB
imageVariable-length binary data. Maximum 2GB
Number types:Data typeDescriptionStorage
tinyintAllows whole numbers from 0 to 2551 byte
smallintAllows whole numbers between -32,768 and 32,7672 bytes
intAllows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
bigintAllows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 8 bytes
decimal(p,s)Fixed precision and scale numbers.
Allows numbers from -10^38 +1 to 10^38 1.
The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 05-17 bytes
numeric(p,s)Fixed precision and scale numbers.
Allows numbers from -10^38 +1 to 10^38 1.
The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 05-17 bytes
smallmoneyMonetary data from -214,748.3648 to 214,748.3647 4 bytes
moneyMonetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.58078 bytes
float(n)Floating precision number data from -1.79E + 308 to 1.79E + 308.
The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.4 or 8 bytes
realFloating precision number data from -3.40E + 38 to 3.40E + 384 bytes
Date types:Data typeDescriptionStorage
datetimeFrom January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds8 bytes
datetime2From January 1, 0001 and December 31, 9999 with an accuracy of 100 nanoseconds6-8 bytes
smalldatetimeFrom January 1, 1900 to June 6, 2079 with an accuracy of 1 minute4 bytes
dateStore a date only. From January 1, 0001 to December 31, 99993 bytes
timeStore a time only to an accuracy of 100 nanoseconds3-5 bytes
datetimeoffsetThe same as datetime2 with the addition of a time zone offset8-10 bytes
timestampStores 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
Other data types:Data typeDescription
sql_variantStores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp
uniqueidentifierStores a globally unique identifier (GUID)
xmlStores XML formatted data. Maximum 2GB
cursorStores a reference to a cursor used for database operations
tableStores a result-set for later processing
SQL Quick Reference
HYPERLINK "http://www.w3schools.com/sql/sql_summary.asp"
SQL Quick Reference from W3Schools. Print it, and fold it in your pocket.
SQL SyntaxStatementSyntax
AND / ORSELECT column_name(s)FROM table_nameWHERE conditionAND|OR condition
ALTER TABLE (add column)ALTER TABLE table_name ADD column_name datatype
ALTER TABLE (drop column)ALTER TABLE table_name DROP COLUMN column_name
AS (alias for column)SELECT column_name AS column_aliasFROM table_name
AS (alias for table)SELECT column_nameFROM table_name AS table_alias
BETWEENSELECT column_name(s)FROM table_nameWHERE column_nameBETWEEN value1 AND value2
CREATE DATABASECREATE DATABASE database_name
CREATE INDEXCREATE INDEX index_nameON table_name (column_name)
CREATE TABLECREATE TABLE table_name(column_name1 data_type,column_name2 data_type,.......)
CREATE UNIQUE INDEXCREATE UNIQUE INDEX index_nameON table_name (column_name)
CREATE VIEWCREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition
DELETE FROMDELETE FROM table_name (Note: Deletes the entire table!!)
orDELETE FROM table_nameWHERE condition
DROP DATABASEDROP DATABASE database_name
DROP INDEXDROP INDEX table_name.index_name
DROP TABLEDROP TABLE table_name
GROUP BYSELECT column_name1,SUM(column_name2)FROM table_nameGROUP BY column_name1
HAVINGSELECT column_name1,SUM(column_name2)FROM table_nameGROUP BY column_name1HAVING SUM(column_name2) condition value
INSELECT column_name(s)FROM table_nameWHERE column_nameIN (value1,value2,..)
INSERT INTOINSERT INTO table_nameVALUES (value1, value2,....)
orINSERT INTO table_name(column_name1, column_name2,...)VALUES (value1, value2,....)
LIKESELECT column_name(s)FROM table_nameWHERE column_nameLIKE pattern
ORDER BYSELECT column_name(s)FROM table_nameORDER BY column_name [ASC|DESC]
SELECTSELECT column_name(s)FROM table_name
SELECT *SELECT *FROM table_name
SELECT DISTINCTSELECT DISTINCT column_name(s)FROM table_name
SELECT INTO(used to create backup copies of tables)SELECT *INTO new_table_nameFROM original_table_name
orSELECT column_name(s)INTO new_table_nameFROM original_table_name
TRUNCATE TABLE(deletes only the data inside the table)TRUNCATE TABLE table_name
UPDATEUPDATE table_nameSET column_name=new_value[, column_name=new_value]WHERE column_name=some_value
WHERESELECT column_name(s)FROM table_nameWHERE condition
Source : http://www.w3schools.com/sql/sql_quickref.asp