Welcome To SQL language
INTRODUCTION TO SQL
Structured Query Language or SQL is a standard Database language which is used to
create, maintain and retrieve the data from relational databases like MySQL,
Oracle, SQL Server, PostGre, etc. The recent ISO standard version of SQL is
SQL:2019.
As the name suggests, it is used when we have structured data (in the form of
tables). All databases that are not relational (or do not use fixed structure
tables to store data) and therefore do not use SQL, are called NoSQL databases.
Examples of NoSQL are MongoDB, DynamoDB, Cassandra, etc
BASIC 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.
In this tutorial we will use the well-known Northwind sample database (included in
MS Access and MS SQL Server).
Below is a selection from the "Customers" table:
SQL Statements
SQL SELCT STATEMENT
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT STATEMENT
SELECT column1, column2, ...
FROM table_name;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
CustomerID |
CustomerName |
ContactName |
Address |
City |
PostalCode |
Country |
1
|
Alfreds Futterkiste |
Maria Anders |
Obere Str. 57 |
Berlin |
12209 |
Germany |
2 |
Ana Trujillo Emparedados y helados |
Ana Trujillo |
Avda. de la Constitución 2222 |
México D.F. |
05021 |
Mexico |
3 |
Antonio Moreno Taquería |
Antonio Moreno |
Mataderos 2312 |
México D.F. |
05023 |
Mexico |
4
|
Around the Horn |
Thomas Hardy |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
5 |
Berglunds snabbköp |
Christina Berglund |
Berguvsvägen 8 |
Luleå |
S-958 22 |
Sweden |
SELECT Column Example
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
SELECT CustomerName, City FROM Customers;
HOW TO SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
SELECT DISTINCT STATEMENT IN SQL
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you
only want to list the different (distinct) values.
SYNTAX
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT Example Without DISTINCT
The following SQL statement selects ALL (including the duplicates) values from the
"Country" column in the "Customers" table:
SELECT Country FROM Customers;
SELECT DISTINCT EXAMPLE
The following SQL statement selects only the DISTINCT values from the "Country"
column in the "Customers" table:
SELECT COUNT(DISTINCT Country) FROM Customers;
Here is the workaround for MS Access:
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
WHERE CLAUSE IN SQL
The WHERE clause is used to filter records.
The WHERE clause is used to extract only those records that fulfill a specified
condition.
SYNTAX
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
SELECT * FROM Customers
WHERE Country='america';
TEXT FIELED VS. NUMERIC FIELED
SQL requires single quotes around text values (most database systems will also allow
double quotes).
However, numeric fields should not be enclosed in quotes:
SELECT * FROM Customers
WHERE CustomerID=1;
Operators in The WHERE Clause
Operator |
Description |
= |
Equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
<> |
Not equal. Note: In some versions of SQL this operator may be
written as != |
BETWEEN |
Between a certain range |
LIKE |
Search for a pattern |
IN |
To specify multiple possible values for a column |
AND , OR ,
NOT OPERTAOR IN SQL
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one
condition:
- The AND operator displays a record if all the conditions separated by AND
are TRUE.
- The OR operator displays a record if any of the conditions separated by OR
is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
AND EXAMPLE
SELECT * FROM Customers
WHERE Country='america' AND City='india';
OR EXAMPLE
SELECT * FROM Customers
WHERE City='america' OR City='india';
NOT EXAMPLE
SELECT * FROM Customers
WHERE NOT Country='america';
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is
"america" AND city must be "Berlin" OR "india" (use parenthesis to form
complex expressions):
SELECT * FROM Customers
WHERE Country='america' AND (City='Berlin' OR City='india');
ORDER BY KEYWORD IN SQL
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
The ORDER BY keyword sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.
syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
example of ORDER BY
The following SQL statement selects all customers from the "Customers" table,
sorted by the "Country" column:
SELECT * FROM Customers
ORDER BY Country;
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table,
sorted by the "Country" and the "CustomerName" column. This means that it orders
by Country, but if some rows have the same Country, it orders them by
CustomerName:
SELECT * FROM Customers
ORDER BY Country, CustomerName;
INSERT INTO STATEMENT IN SQL
The INSERT INTO statement is used to insert new records in a table.
syntax
It is possible to write the INSERT INTO statement in two ways.
The first way specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
INSERT INTO STATEMENT IN SQL
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006',
'Norway');
NULL VALUES IN SQL
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or
update a record without adding a value to this field. Then, the field will be
saved with a NULL value.
syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
SQL TOP, LIMIT or ROWNUM Clause
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning
a large number of records can impact performance.
SQL Server / MS Access Syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
SQL TOP, LIMIT and ROWNUM Examples
The following SQL statement selects the first three records from the "Customers"
table (for SQL Server/MS Access):
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the LIMIT clause (for
MySQL):
SELECT * FROM Customers
LIMIT 3;
SQL TOP PERCENT Example
The following SQL statement selects the first 50% of the records from the
"Customers" table (for SQL Server/MS Access):
SELECT TOP 50 PERCENT * FROM Customers;
ADD a WHERE CLAUSE
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
UPDATE STATEMENT IN SQL
The UPDATE statement is used to modify the existing records in a table.
syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE TABLE
The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.
UPDATE Customers
SET ContactName = 'Jhon Smith', City= 'lost fransisco'
WHERE CustomerID = 1;
HOW TO UPDATE MUILTIPLE RECORD
It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the contactname to "kartik" for all
records where country is "india":
UPDATE Customers
SET ContactName='kartik'
WHERE Country='india';
DELETE STATEMENT IN SQL
The DELETE statement is used to delete existing records in a table.
syntax
DELETE FROM table_name WHERE condition;
SQL DELETE Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
MIN() AND MAX() FUNCTION IN SQL
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() SYNTAX
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MIN() EXAMPLE
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
SQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.
syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
IN operator in SQL
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
BETWEEN OPERATORS IN SQL
The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
BETWEEN Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
NOT BETWEEN Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
JOINS IN SQL
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
Let's look at a selection from the "Orders" table:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
INNER JOIN KEYWORD IN SQL
The INNER JOIN keyword selects records that have matching values in both tables.
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
LEFT JOIN KEYWORD IN SQL
The LEFT JOIN keyword returns all records from the left table (table1), and the
matched records from the right table (table2). The result is NULL from the right
side, if there is no match.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
RIGHT JOIN KEYWORD IN SQL
The RIGHT JOIN keyword returns all records from the left table (table1), and the
matched records from the right table (table2). The result is NULL from the right
side, if there is no match.
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
FULL OUTER JOIN KEYWORD IN SQL
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SELF JOIN KEYWORD IN SQL
A self JOIN is a regular join, but the table is joined with itself.
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
THE GROUP BY() STATMENT IN SQL
The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
HAVING CLAUSE IN SQL
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns true if the subquery returns one or more records.
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
ANY AND ALL OPERATORS IN SQL
The ANY and ALL operators are used with a WHERE or HAVING clause.
The ANY operator returns true if any of the subquery values meet the condition
The ALL operator returns true if all of the subquery values meet the condition.
ANY operator example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
ALL operator example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
CASE STATEMENT IN SQL
The CASE statement goes through conditions and returns a value when the first
condition is met (like an IF-THEN-ELSE statement). So, once a condition is true,
it will stop reading and return the result. If no conditions are true, it
returns the value in the ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
SQL Stored Procedures for SQL Server
A stored procedure is a prepared SQL code that you can save, so the code can be
reused over and over again.
So if you have an SQL query that you write over and over again, save it as a stored
procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can
act based on the parameter value(s) that is passed.
Stored Procedure Example
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Stored Procedure With One Parameter
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Stored Procedure With Multiple Parameters
Setting up multiple parameters is very easy. Just list each parameter and the data
type separated by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers from a
particular City with a particular PostalCode from the "Customers" table:
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
COMMENT IN SQL
Comments are used to explain sections of SQL statements, or to prevent execution of
SQL statements.
SINGLE LINE comment
MULITY LINE comment
OPERATORS IN SQL
SQL Arithmetic Operators
Operator |
Description |
+ |
Add |
- |
Subtract |
* |
Multiply |
/ |
Divide |
% |
Modulo |
SQL Bitwise Operators
Operator |
Description |
& |
Bitwise AND |
| |
Bitwise OR |
^ |
Bitwise exclusive OR |
SQL Comparison Operators
Operator |
Description |
= |
Equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
<> |
Not equal to |
SQL Comparison Operators
Operator |
Description |
+= |
Add equals |
-= |
Subtract equals |
*= |
Multiply equals |
/= |
Divide equals |
%= |
Modulo equals |
&= |
Bitwise AND equals |
^-= |
Bitwise exclusive equals |
|*= |
Bitwise OR equals |
SQL Logical Operators
Operator |
Description |
ALL |
TRUE if all of the subquery values meet the condition |
AND |
TRUE if all the conditions separated by AND is TRUE |
ANY |
TRUE if any of the subquery values meet the condition |
BETWEEN |
TRUE if the operand is within the range of comparisons |
EXISTS |
TRUE if the subquery returns one or more records |
IN |
TRUE if the operand is equal to one of a list of expressions |
LIKE |
TRUE if the operand matches a pattern |
NOT |
Displays a record if the condition(s) is NOT TRUE |
OR |
TRUE if any of the conditions separated by OR is TRUE |
SOME |
TRUE if any of the subquery values meet the condition |
SQL DATABASE
CREATE DATABASE STATEMENT IN SQL
The CREATE DATABASE statement is used to create a new SQL
databases.
EXAMPLE
CREATE DATABASE codolearnDB;
DROP DATABASE STATEMENT IN SQL
The DROP DATABASE statement is used to drop an existing SQL database.
EXAMPLE
DROP DATABASE codolearnDB;
BACK UP DATABASE FOR SQL SERVER
The BACKUP DATABASE statement is used in SQL Server to create a full back up of an
existing SQL database.
The SQL BACKUP WITH DIFFERENTIAL Statement
A differential back up only backs up the parts of the database that have changed
since the last full database backup.
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
BACKUP DATABASE Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
BACKUP WITH DIFFERENTIAL Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
CREATE TABLE STATEMENT USING SQL
The CREATE TABLE statement is used to create a new table in a database.
SYNTAX
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
DROP TABLE STATEMENT IN SQL
The DROP TABLE statement is used to drop an existing table in a database.
syntax
SQL DROP TABLE Example
The following SQL statement drops the existing table "Shippers":
SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself.
TRUNCATE TABLE table_name;
SQL ALTER TABLE Statement
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
The ALTER TABLE statement is also used to add and drop various constraints on
an existing table.
ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:
ALTER
TABLE
table_name
ADD
column_name datatype;
The following SQL adds an "Email" column to the "Customers" table:
Example
ALTER TABLE
Customers
ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some
database systems don't allow deleting a column):
ALTER
TABLE
table_name
DROP
COLUMN
column_name;
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE
Customers
DROP COLUMN
Email;
ALTER TABLE - ALTER/MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
ALTER
TABLE
table_name
ALTER
COLUMN
column_name datatype;
My SQL / Oracle (prior version 10G):
ALTER
TABLE
table_name
MODIFY
COLUMN
column_name datatype;
Oracle 10G and later:
ALTER
TABLE
table_name
MODIFY
column_name datatype;
SQL ALTER TABLE Example
Look at the "Persons" table:
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 add a column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ALTER
TABLE
Persons
ADD
DateOfBirth date;
The "Persons" table will now look like this:
ID |
LastName |
FirstName |
Address |
City |
DateOfBirth |
1 |
Hansen |
Ola |
Timoteivn 10 |
Sandnes |
|
2 |
Svendson |
Tove |
Borgvn 23 |
Sandnes |
|
3 |
Pettersen |
Kari |
Storgt 20 |
Stavanger |
|
Change Data Type Example
Now we want to change the data type of the column named "DateOfBirth" in the
"Persons" table.
We use the following SQL statement:
ALTER
TABLE
Persons
ALTER
COLUMN
DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold
a year in a two- or four-digit format.
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons"
table.
We use the following SQL statement:
ALTER
TABLE
Persons
DROP
COLUMN
DateOfBirth;
The "Persons" table will now look like this:
ID |
LastName |
FirstName |
Address |
City |
1 |
Hansen |
Ola |
Timoteivn 10 |
Sandnes |
2 |
Svendson |
Tove |
Borgvn 23 |
Sandnes |
3 |
Pettersen |
Kari |
Storgt 20 |
Stavanger |
CONSTRAINTS IN SQL
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply
to a column, and table level constraints apply to the whole table.
commonly used Constraints :
- NOT NULL - Ensures that a column cannot have a NULL
value
- UNIQUE - Ensures that all values in a column are
different
- PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
- FOREIGN KEY - Uniquely identifies a row/record in
another
table
- CHECK - Ensures that all values in a column satisfies a
specific condition
- DEFAULT - Sets a default value for a column when no
value
is specified
- INDEX - Used to create and retrieve data from the
database
very quickly
NOT NULL CONSTRAINT IN SQL
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert
a new record, or update a record without adding a value to this field.
SQL NOT NULL on CREATE TABLE
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will
NOT accept NULL values when the "Persons" table is created:
example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table is
already created, use the following SQL:
ALTER TABLE Persons
MODIFY Age int NOT NULL;
SQL UNIQUE Constraint
SQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "ID" column when the
"Persons" table is created:
SQL Server / Oracle / MS Access:
CREATE
TABLE
Persons
(
ID int NOT NULL
UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
MySQL:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE
(ID)
);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE
(ID,LastName)
);
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "ID" column when the table is already
created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
ADD
UNIQUE
(ID);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
ADD
CONSTRAINT UC_Person UNIQUE
(ID,LastName);
DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:
MySQL:
ALTER
TABLE
Persons
DROP
INDEX
UC_Person;
SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
DROP
CONSTRAINT UC_Person;
SQL PRIMARY KEY Constraint
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
SQL PRIMARY KEY on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons"
table is created:
MySQL:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY
(ID)
);
SQL Server / Oracle / MS Access:
CREATE
TABLE
Persons
(
ID int NOT NULL
PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY
KEY
(ID,LastName)
);
Note: If you use the ALTER TABLE statement to add a primary key, the
primary key column(s) must
already have been declared to not contain NULL values (when the table was
first created).
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
MySQL:
ALTER
TABLE
Persons
DROP
PRIMARY KEY;
SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
DROP
CONSTRAINT PK_Person;
SQL FOREIGN KEY Constraint
SQL FOREIGN KEY Constraint
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers
to
the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
Look at the following two tables:
"Persons" table:
PersonID |
LastName |
FirstName |
Age |
1 |
Hansen |
Ola |
30 |
2 |
Svendson |
Tove |
23 |
3 |
Pettersen |
Kari |
20 |
"Orders" table:
OrderID |
OrderNumber |
PersonID |
1 |
77895 |
3 |
2 |
44678 |
3 |
3 |
22456 |
2 |
4 |
24562 |
1 |
Notice that the "PersonID" column in the "Orders" table points to the
"PersonID" column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.
The "PersonID" 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 invalid data from being inserted
into the foreign key column,
because it has to be one of the values contained in the table it points to.
SQL FOREIGN KEY on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "PersonID" column when the
"Orders" table is created:
MySQL:
CREATE
TABLE
Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY
(OrderID),
FOREIGN KEY
(PersonID) REFERENCES
Persons(PersonID)
);
SQL Server / Oracle / MS Access:
CREATE
TABLE
Orders
(
OrderID int NOT NULL
PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY
REFERENCES
Persons(PersonID)
);
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:
CREATE
TABLE
Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY
(OrderID),
CONSTRAINT FK_PersonOrder FOREIGN
KEY
(PersonID)
REFERENCES
Persons(PersonID)
);
SQL FOREIGN KEY on ALTER TABLE
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders"
table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER
TABLE
Orders
ADD
FOREIGN KEY
(PersonID)
REFERENCES Persons(PersonID);
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_PersonOrder
FOREIGN KEY
(PersonID)
REFERENCES Persons(PersonID);
DROP a FOREIGN KEY Constraint
To drop a FOREIGN KEY constraint, use the following SQL:
MySQL:
ALTER
TABLE
Orders
DROP
FOREIGN KEY
FK_PersonOrder;
SQL Server / Oracle / MS Access:
ALTER
TABLE
Orders
DROP
CONSTRAINT FK_PersonOrder;
SQL CHECK Constraint
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a
column.
If you define a CHECK constraint on a single column it allows only certain
values for this column.
If you define a CHECK constraint on a table it can limit the values in
certain columns based on values in other columns in the row.
SQL CHECK on CREATE TABLE
The following SQL creates a CHECK constraint on the "Age" column when the
"Persons" table is created.
The CHECK constraint ensures that the age of a person must be 18, or older:
MySQL:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK
(Age>=18)
);
SQL Server / Oracle / MS Access:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
To allow naming of a CHECK constraint, and for defining a CHECK constraint on
multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK
(Age>=18 AND
City='Sandnes')
);
SQL CHECK on ALTER TABLE
To create a CHECK constraint on the "Age" column when the table is already
created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
ADD
CHECK
(Age>=18);
To allow naming of a CHECK constraint, and for defining a CHECK constraint on
multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
ADD
CONSTRAINT CHK_PersonAge CHECK
(Age>=18 AND
City='Sandnes');
DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
DROP
CONSTRAINT CHK_PersonAge;
MySQL:
ALTER
TABLE
Persons
DROP
CHECK
CHK_PersonAge;
SQL DEFAULT Constraint
SQL DEFAULT Constraint
The DEFAULT constraint is used to provide a default value for a column.
The default value will be added to all new records IF no other value is
specified.
SQL DEFAULT on CREATE TABLE
The following SQL sets a DEFAULT value for the "City" column when the
"Persons" table is created:
My SQL / SQL Server / Oracle / MS Access:
CREATE
TABLE
Persons
(
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255)
DEFAULT 'Sandnes'
);
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
CREATE
TABLE
Orders
(
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);
SQL DEFAULT on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already
created, use the following SQL:
MySQL:
ALTER
TABLE
Persons
ALTER
City SET DEFAULT
'Sandnes';
SQL Server:
ALTER
TABLE
Persons
ADD CONSTRAINT df_City
DEFAULT
'Sandnes'
FOR City;
MS Access:
ALTER
TABLE
Persons
ALTER
COLUMN
City SET DEFAULT
'Sandnes';
Oracle:
ALTER
TABLE
Persons
MODIFY
City DEFAULT 'Sandnes';
DROP a DEFAULT Constraint
To drop a DEFAULT constraint, use the following SQL:
MySQL:
ALTER
TABLE
Persons
ALTER
City DROP DEFAULT;
SQL Server / Oracle / MS Access:
ALTER
TABLE
Persons
ALTER
COLUMN
City DROP DEFAULT;
SQL CREATE INDEX Statement
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.
Indexes are used to retrieve data from the database more quickly than
otherwise. 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, only create indexes on columns that will be frequently searched
against.
CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE
INDEX
index_name
ON
table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE
UNIQUE
INDEX
index_name
ON
table_name (column1, column2, ...);
Note: The syntax for creating indexes varies among different
databases. Therefore: Check the syntax for creating indexes in your
database.
CREATE INDEX Example
The SQL statement below creates an index named "idx_lastname" on the
"LastName" column in the "Persons" table:
CREATE
INDEX
idx_lastname
ON
Persons (LastName);
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
CREATE
INDEX
idx_pname
ON
Persons (LastName, FirstName);
DROP INDEX Statement
The DROP INDEX statement is used to delete an index in a table.
MS Access:
DROP
INDEX
index_name ON table_name;
SQL Server:
DROP
INDEX
table_name.index_name;
DB2/Oracle:
MySQL:
ALTER
TABLE
table_name
DROP INDEX
index_name;
SQL AUTO INCREMENT Field
AUTO INCREMENT Field
Auto-increment allows a unique number to be generated automatically when a
new record is inserted into a table.
Often this is the primary key field that we would like to be created
automatically every time a new record is inserted.
Syntax for MySQL
The following SQL statement defines the "Personid" column to be an
auto-increment primary key field in the "Persons" table:
CREATE
TABLE
Persons
(
Personid int NOT NULL
AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY
(Personid)
);
MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.
By default, the starting value for AUTO_INCREMENT is 1, and it will increment
by 1 for each new record.
To let the AUTO_INCREMENT sequence start with another value, use the
following SQL statement:
ALTER
TABLE
Persons AUTO_INCREMENT=100;
To insert a new record into the "Persons" table, we will NOT have to specify
a value for the "Personid"
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
"Personid" column would be assigned a unique value. The "FirstName" column
would be set to
"Lars" and the "LastName" column would be set to "Monsen".
Syntax for SQL Server
The following SQL statement defines the "Personid" column to be an
auto-increment primary key field in the "Persons" table:
CREATE
TABLE
Persons
(
Personid int IDENTITY(1,1) PRIMARY
KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment
feature.
In the example above, the starting value for IDENTITY is 1, and it will
increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at
value 10 and increment by 5, change
it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify
a value for the "Personid" 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
"Personid" column would be assigned a unique value. The "FirstName" column
would be set to
"Lars" and the "LastName" column would be set to "Monsen".
Syntax for Access
The following SQL statement defines the "Personid" column to be an
auto-increment primary key field in the "Persons" table:
CREATE
TABLE
Persons
(
Personid AUTOINCREMENT PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
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.
Tip: To specify that the "Personid" 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 "Personid" 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
"Personid" column would be assigned a unique value. The "FirstName" column
would be set to
"Lars" and the "LastName" column would be set to "Monsen".
Syntax for Oracle
In Oracle the code is a little bit more tricky.
You will have to create an auto-increment field with the sequence object
(this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE
SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
The code above creates a sequence object called seq_person, that starts with
1 and will increment by 1.
It will also cache up to 10 values for performance. The cache option
specifies how many sequence values will be stored in memory for faster
access.
To insert a new record into the "Persons" table, we will have to use the
nextval function (this function retrieves the next value from seq_person
sequence):
INSERT
INTO
Persons (Personid,FirstName,LastName)
VALUES
(seq_person.nextval,'Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned the next number from the seq_person
sequence. The "FirstName" column would be set to "Lars" and the "LastName"
column would be set to "Monsen".
SQL Working With Dates
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.
SQL Date Data Types
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
more complicated.
MySQL comes with the following data types for storing a date or a
date/time value in the database:
- DATE - format YYYY-MM-DD
- DATETIME - format: YYYY-MM-DD HH:MI:SS
- TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
- YEAR - format YYYY or YY
SQL Server comes with the following data types for storing a date or a
date/time value in the database:
- DATE - format YYYY-MM-DD
- DATETIME - format: YYYY-MM-DD HH:MI:SS
- SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
- TIMESTAMP - format: a unique number
Note: The date types are chosen for a column when you create a new
table in your database!
SQL Working with Dates
You can compare two dates easily if there is no time component involved!
Assume we have the following "Orders" table:
OrderId |
ProductName |
OrderDate |
1 |
Geitost |
2008-11-11 |
2 |
Camembert Pierrot |
2008-11-09 |
3 |
Mozzarella di Giovanni |
2008-11-11 |
4 |
Mascarpone Fabioli |
2008-10-29 |
Now we want to select the records with an OrderDate of "2008-11-11" from the
table above.
We use the following SELECT statement:
SELECT
* FROM
Orders WHERE OrderDate='2008-11-11'
The result-set will look like this:
OrderId |
ProductName |
OrderDate |
1 |
Geitost |
2008-11-11 |
3 |
Mozzarella di Giovanni |
2008-11-11 |
Now, assume that the "Orders" table looks like this (notice the time
component in the "OrderDate" column):
OrderId |
ProductName |
OrderDate |
1 |
Geitost |
2008-11-11 13:23:44 |
2 |
Camembert Pierrot |
2008-11-09 15:45:21 |
3 |
Mozzarella di Giovanni |
2008-11-11 11:12:01 |
4 |
Mascarpone Fabioli |
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: To keep your queries simple and easy to maintain, do not allow
time components in your dates!
SQL Views
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL
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 one single table.
CREATE VIEW Syntax
CREATE
VIEW
view_name AS
SELECT
column1, column2, ...
FROM
table_name
WHERE
condition;
Note: A view always shows up-to-date data! The database engine
recreates the data, using the view's SQL statement, every time a user
queries a view.
SQL CREATE VIEW Examples
The following SQL creates a view that shows all customers from Brazil:
Example
CREATE
VIEW
[Brazil
Customers] AS
SELECT
CustomerName, ContactName
FROM
Customers
WHERE
Country = 'Brazil';
We can query the view above as follows:
Example
SELECT
* FROM
[Brazil
Customers];
table with a price higher than the average price:
Example
CREATE
VIEW
[Products Above Average Price] AS
SELECT
ProductName, Price
FROM
Products
WHERE
Price > (SELECT AVG(Price) FROM
Products);
We can query the view above as follows:
Example
SELECT
* FROM
[Products Above Average Price];
SQL Updating a View
A view can be updated with the CREATE OR REPLACE VIEW command.
SQL CREATE OR REPLACE VIEW Syntax
CREATE
OR
REPLACE VIEW
view_name AS
SELECT
column1, column2, ...
FROM
table_name
WHERE
condition;
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE
OR
REPLACE VIEW
[Brazil Customers] AS
SELECT
CustomerName, ContactName, City
FROM
Customers
WHERE
Country = 'Brazil';
SQL Dropping a View
A view is deleted with the DROP VIEW command.
SQL DROP VIEW Syntax
The following SQL drops the "Brazil Customers" view:
Example
DROP
VIEW
[Brazil Customers];
SQL Hosting
If you want your web site to be able to store and retrieve data from a
database, your web server should have access to a database-system that uses
the
SQL language.
If your web server is hosted by an Internet Service Provider (ISP), you will
have to look for SQL hosting plans.
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and
MS Access.
MS SQL Server
Microsoft's SQL Server is a popular database software for database-driven web
sites
with high traffic.
SQL Server is a very powerful, robust and full featured SQL database system.
Oracle
Oracle is also a popular database software for database-driven web sites
with high traffic.
Oracle is a very powerful, robust and full featured SQL database system.
MySQL
MySQL is also a popular database software for web sites.
MySQL is a very powerful, robust and full featured SQL database system.
MySQL is an inexpensive
alternative to the expensive Microsoft and Oracle solutions.
Access
When a web site requires only a simple database, Microsoft Access can be a
solution.
Access is not well suited for very high-traffic, and not as powerful as
MySQL, SQL Server, or Oracle.
SQL Data Types for MySQL, SQL Server, and MS
Access
The data type of a column defines what value the column can
hold:
integer, character, money, date and time, binary,
and so on.
SQL Data Types
Each column in a database table is required to have a name and a data type.
An SQL developer must decide what type of data that will be stored inside
each
column when creating a table. The data type is a
guideline for SQL to understand what type of data is expected inside of each
column, and it also identifies how SQL will interact with the stored data.
Note: Data types might have different names in different
database.
And even if the name is the same, the size and other details may be
different!
Always check the
documentation!
MySQL Data Types (Version 8.0)
In MySQL there are three main data types: string, numeric, and date and time.
String data types:
Data type |
Description |
CHAR(size) |
A FIXED length string (can contain letters, numbers, and
special characters). The
size parameter specifies the column length in
characters - can be
from 0 to 255. Default is 1
|
VARCHAR(size) |
A VARIABLE length string (can contain letters, numbers, and
special
characters). The size parameter specifies the
maximum column
length in characters - can be from 0 to 65535 |
BINARY(size) |
Equal to CHAR(), but stores binary byte strings. The
size
parameter specifies the column length in bytes. Default is 1
|
VARBINARY(size) |
Equal to VARCHAR(), but stores binary byte strings. The
size
parameter specifies the maximum column length in bytes.
|
TINYBLOB |
For BLOBs (Binary Large OBjects). Max length: 255 bytes |
TINYTEXT |
Holds a string with a maximum length of 255 characters |
TEXT(size) |
Holds a string with a maximum length of 65,535 bytes |
BLOB(size) |
For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes
of data |
MEDIUMTEXT |
Holds a string with a maximum length of 16,777,215
characters |
MEDIUMBLOB |
For BLOBs (Binary Large OBjects). Holds up to 16,777,215
bytes of data |
LONGTEXT |
Holds a string with a maximum length of 4,294,967,295
characters |
LONGBLOB |
For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295
bytes of data |
ENUM(val1, val2, val3, ...) |
A string object that can have only one value, chosen from 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.
The values are sorted in the order you enter them |
SET(val1, val2, val3, ...) |
A string object that can have 0 or more values, chosen from
a list of
possible values. You can list up to 64 values in a SET list
|
Numeric data types:
Data type |
Description |
BIT(size) |
A bit-value type. The number of bits per value is specified
in size.
The size parameter can hold a value from 1 to 64.
The default
value for size is 1. |
TINYINT(size) |
A very small integer. Signed range is from -128 to 127.
Unsigned range
is from 0 to 255. The size parameter specifies the
maximum
display width (which is 255) |
BOOL |
Zero is considered as false, nonzero values are considered
as true. |
BOOLEAN |
Equal to BOOL |
SMALLINT(size) |
A small integer. Signed range is from -32768 to 32767.
Unsigned range
is from 0 to 65535. The size parameter specifies
the maximum
display width (which is 255) |
MEDIUMINT(size) |
A medium integer. Signed range is from -8388608 to 8388607.
Unsigned
range is from 0 to 16777215. The size parameter
specifies the
maximum display width (which is 255) |
INT(size) |
A medium integer. Signed range is from -2147483648 to
2147483647.
Unsigned range is from 0 to 4294967295. The size
parameter
specifies the maximum display width (which is 255) |
INTEGER(size) |
Equal to INT(size) |
BIGINT(size) |
A large integer. Signed range is from -9223372036854775808
to
9223372036854775807. Unsigned range is from 0 to
18446744073709551615. The
size parameter specifies the maximum display width
(which is 255)
|
FLOAT(size, d) |
A floating point number. The total number of digits is
specified in
size. The number of digits after the decimal point
is specified
in the d parameter. This syntax is deprecated in
MySQL 8.0.17,
and it will be removed in future MySQL versions
|
FLOAT(p) |
A floating point number. MySQL uses the p value to
determine
whether to use FLOAT or DOUBLE for the resulting data type.
If p
is from 0 to 24, the data type becomes FLOAT(). If
p is from 25 to
53, the data type becomes DOUBLE()
|
DOUBLE(size, d) |
A normal-size floating point number. The total number of
digits is specified in
size. The number of digits after the decimal point
is specified
in the d parameter
|
DOUBLE PRECISION(size, d) |
|
DECIMAL(size, d) |
An exact fixed-point number. The total number of digits is
specified in
size. The number of digits after the decimal point
is specified
in the d parameter. The maximum number for
size is 65.
The maximum number for d is 30. The default value
for size
is 10. The default value for d is 0.
|
DEC(size, d) |
Equal to DECIMAL(size,d) |
Note: All the numeric data types may have an extra option:
UNSIGNED
or ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values
for
the column. If you add the ZEROFILL option, MySQL automatically also adds
the
UNSIGNED attribute to the column.
Date and Time data types:
Data type |
Description |
DATE |
A date. Format: YYYY-MM-DD. The supported range is from
'1000-01-01' to '9999-12-31' |
DATETIME(fsp) |
A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The
supported range is from '1000-01-01 00:00:00' to '9999-12-31
23:59:59'.
Adding DEFAULT and ON UPDATE in the column definition to get
automatic
initialization and updating to the current date and time |
TIMESTAMP(fsp) |
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. The supported range is from '1970-01-01 00:00:01' UTC
to '2038-01-09 03:14:07' UTC.
Automatic initialization and updating to the current date and
time can be
specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE
CURRENT_TIMESTAMP
in the column definition |
TIME(fsp) |
A time. Format: hh:mm:ss. The supported range is from
'-838:59:59' to '838:59:59' |
YEAR |
A year in four-digit format. Values allowed in four-digit
format: 1901 to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format. |
SQL Server Data Types
String data types:
Data type |
Description |
Max size |
Storage |
char(n) |
Fixed width character string |
8,000 characters |
Defined width |
varchar(n) |
Variable width character string |
8,000 characters |
2 bytes + number of chars |
varchar(max) |
Variable width character string |
1,073,741,824 characters |
2 bytes + number of chars |
text |
Variable width character string |
2GB of text data |
4 bytes + number of chars |
nchar |
Fixed width Unicode string |
4,000 characters |
Defined width x 2 |
nvarchar |
Variable width Unicode string |
4,000 characters |
|
nvarchar(max) |
Variable width Unicode string |
536,870,912 characters |
|
ntext |
Variable width Unicode string |
2GB of text data |
|
binary(n) |
Fixed width binary string |
8,000 bytes |
|
varbinary |
Variable width binary string |
8,000 bytes |
|
varbinary(max) |
Variable width binary string |
2GB |
|
image |
Variable width binary string |
2GB |
|
Numeric data types:
Data type |
Description |
Storage |
bit |
Integer that can be 0, 1, or NULL |
|
tinyint |
Allows whole numbers from 0 to 255 |
1 byte |
smallint |
Allows whole numbers between -32,768 and 32,767 |
2 bytes |
int |
Allows whole numbers between -2,147,483,648 and
2,147,483,647 |
4 bytes |
bigint |
Allows 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 0
|
5-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 0
|
5-17 bytes |
smallmoney |
Monetary data from -214,748.3648 to 214,748.3647 |
4 bytes |
money |
Monetary data from -922,337,203,685,477.5808 to
922,337,203,685,477.5807 |
8 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 |
real |
Floating precision number data from -3.40E + 38 to 3.40E +
38 |
4 bytes |
Date and Time data types:
Data type |
Description |
Storage |
datetime |
From January 1, 1753 to December 31, 9999 with an accuracy
of 3.33 milliseconds |
8 bytes |
datetime2 |
From January 1, 0001 to December 31, 9999 with an accuracy
of 100 nanoseconds |
6-8 bytes |
smalldatetime |
From January 1, 1900 to June 6, 2079 with an accuracy of 1
minute |
4 bytes |
date |
Store a date only. From January 1, 0001 to December 31, 9999
|
3 bytes |
time |
Store a time only to an accuracy of 100 nanoseconds |
3-5 bytes |
datetimeoffset |
The same as datetime2 with the addition of a time zone
offset |
8-10 bytes |
timestamp |
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 |
|
Other data types:
Data type |
Description |
sql_variant |
Stores up to 8,000 bytes of data of various data types, except
text, ntext, and timestamp |
uniqueidentifier |
Stores a globally unique identifier (GUID) |
xml |
Stores XML formatted data. Maximum 2GB |
cursor |
Stores a reference to a cursor used for database operations |
table |
Stores a result-set for later processing |
Microsoft Access Data Types
Data type |
Description |
Storage |
Text |
Use for text or combinations of text and numbers. 255
characters maximum |
|
Memo |
Memo is used for larger amounts of text. Stores up to 65,536
characters. Note: You cannot sort a memo field.
However, they are searchable |
|
Byte |
Allows whole numbers from 0 to 255 |
1 byte |
Integer |
Allows whole numbers between -32,768 and 32,767 |
2 bytes |
Long |
Allows whole numbers between -2,147,483,648 and
2,147,483,647 |
4 bytes |
Single |
Single precision floating-point. Will handle most decimals
|
4 bytes |
Double |
Double precision floating-point. Will handle most decimals
|
8 bytes |
Currency |
Use for currency. Holds up to 15 digits of whole dollars,
plus 4 decimal places. Tip: You can choose which
country's currency to use |
8 bytes |
AutoNumber |
AutoNumber fields automatically give each record its own
number, usually starting at 1 |
4 bytes |
Date/Time |
Use for dates and times |
8 bytes |
Yes/No |
A 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 fields |
1 bit |
Ole Object |
Can store pictures, audio, video, or other BLOBs (Binary
Large OBjects) |
up to 1GB |
Hyperlink |
Contain links to other files, including web pages |
|
Lookup Wizard |
Let you type a list of options, which can then be chosen
from a drop-down list |
4 bytes |