• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/254

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

254 Cards in this Set

  • Front
  • Back
RDBMS
Relational Database Management System
DML
DDL
Data Manipulation Language (DML)
Data Definition Language (DDL)
SQL SELECT Syntax
SELECT column_name(s)
FROM table_name
SELECT * FROM table_name
SQL SELECT Syntax
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SELECT LastName,FirstName FROM Persons (exmp)
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SELECT * FROM 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
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SELECT * FROM Persons
WHERE City='Sandnes'
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
Operators Allowed in the WHERE Clause
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the columns
OR Operator Example
SELECT * FROM Persons
WHERE FirstName='Tove'
OR FirstName='Ola
Combining AND & OR
SELECT * FROM Persons WHERE
LastName='Svendson'
AND (FirstName='Tove' OR FirstName='Ola')
The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified column.
SQL ORDER BY Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
SQL ORDER BY Syntax with SELECT statement
SELECT * FROM Persons
ORDER BY LastName
ORDER BY DESC Example
Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.

SELECT * FROM Persons
ORDER BY LastName DESC
SQL INSERT INTO Syntax v1
INSERT INTO table_name
VALUES (value1, value2, value3,...)
SQL INSERT INTO Syntax v2
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
Insert Data Only in Specified Columns
INSERT INTO Persons (P_Id, LastName, FirstName)
VALUES (5, 'Tjessem', 'Jakob')
The UPDATE Statement
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
The DELETE Statement
DELETE FROM table_name
WHERE some_column=some_value
SQL DELETE Example

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 Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'

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 Johan Bakken 2 Stavanger
Delete All Rows
DELETE FROM table_name

or

DELETE * FROM table_name
The TOP Clause
SELECT TOP number|percent column_name(s)
FROM table_name
TOP Clause example
SELECT *
FROM Persons
LIMIT 5
SQL LIKE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
LIKE Operator Example

P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons
WHERE City LIKE 's%'

P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
SQL Wildcards
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist]
or

[!charlist]

Any single character not in charlist
SQL Wildcard Examples
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SELECT * FROM Persons
WHERE City LIKE 'sa%'
Using the _ Wildcard
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SELECT * FROM Persons
WHERE FirstName LIKE '_la'

P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
Using the [charlist] Wildcard
Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons
WHERE LastName LIKE '[bsp]%'
Using the [charlist] Wildcard not
we want to select the persons with a last name that do not start with "b" or "s" or "p" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons
WHERE LastName LIKE '[!bsp]%'
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
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen')

P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
The BETWEEN Operator
The BETWEEN Operator

The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.

SQL BETWEEN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
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.
SQL Alias Syntax for Tables
SELECT column_name(s)
FROM table_name
AS alias_name
SQL Alias Syntax for Columns
SELECT column_name AS alias_name
FROM table_name
Different SQL JOINs
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables
SQL INNER JOIN Keyword
The INNER JOIN keyword return rows when there is at least one match in both tables.
SQL INNER JOIN Syntax
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SQL INNER JOIN Example

P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).
SQL LEFT JOIN Example

P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
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
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
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
The "Orders" table:

O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
34764
SQL FULL JOIN Keyword
The FULL JOIN keyword return rows when there is a match in one of the tables.
SQL FULL JOIN Syntax
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SQL FULL JOIN 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
The "Orders" table:

O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svendson Tove
34764
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.

Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
SQL UNION Example
E_ID E_Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari

E_ID E_Name
01 Turner, Sally
02 Kent, Clark
03 Svendson, Stephen
04 Scott, Stephen

SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA

E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
The SQL SELECT INTO Statement
The SELECT INTO statement selects data from one table and inserts it into a different table.

The SELECT INTO statement is most often used to create backup copies of tables.
SQL SELECT INTO Syntax
We can select all columns into the new table:

SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename
Or we can select only the columns we want into the new table:

SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_tablename
SQL SELECT INTO Example
Make a Backup Copy - Now we want to make an exact copy of the data in our "Persons" table.

We use the following SQL statement:

SELECT *
INTO Persons_Backup
FROM Persons
We can also use the IN clause to copy the table into another database:

SELECT *
INTO Persons_Backup IN 'Backup.mdb'
FROM Persons
We can also copy only a few fields into the new table:

SELECT LastName,FirstName
INTO Persons_Backup
FROM Persons
SQL SELECT INTO - With a WHERE Clause
SELECT LastName,Firstname
INTO Persons_Backup
FROM Persons
WHERE City='Sandnes'
SQL SELECT INTO - Joined Tables
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
SQL CREATE DATABASE Syntax
CREATE DATABASE database_name
SQL CREATE TABLE Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
CREATE TABLE Example
CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
SQL Constraints main types
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values.

The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.
SQL NOT NULL Constraint Example
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.

The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
SQL UNIQUE Constraint on CREATE TABLE
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
SQL UNIQUE Constraint on ALTER TABLE
ALTER TABLE Persons
ADD UNIQUE (P_Id)
to DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:

MySQL:

ALTER TABLE Persons
DROP INDEX uc_PersonID
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

Each table should have a primary key, and each table can have only ONE primary key.
SQL PRIMARY KEY Constraint on CREATE TABLE
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
SQL PRIMARY KEY Constraint on ALTER TABLE
ALTER TABLE Persons
ADD PRIMARY KEY (P_Id)
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax
ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
To DROP a PRIMARY KEY Constraint
ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
SQL FOREIGN KEY Constraint on CREATE TABLE
CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL synta
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
SQL FOREIGN KEY Constraint on ALTER TABLE
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL:

ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To DROP a FOREIGN KEY Constraint
ALTER TABLE Orders
DROP CONSTRAINT fk_PerOrders
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 Constraint on CREATE TABLE

The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0.
CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)
SQL CHECK Constraint on ALTER TABLE
To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ADD CHECK (P_Id>0)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax
ALTER TABLE Persons
ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
To DROP a CHECK Constraint
ALTER TABLE Persons
DROP CONSTRAINT chk_Person
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.

The default value will be added to all new records, if no other value is specified.
SQL DEFAULT Constraint on CREATE TABLE
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created:

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE()
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
SQL DEFAULT Constraint on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'SANDNES'
To DROP a DEFAULT Constraint
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.

Indexes allow the database application to find data fast; without reading the whole table.
SQL CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name
ON table_name (column_name)
CREATE INDEX Example
The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons" table:

CREATE INDEX PIndex
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 PIndex
ON Persons (LastName, FirstName)
create an index on a combination of columns
CREATE INDEX PIndex
ON Persons (LastName, FirstName)
DROP INDEX Syntax for MS SQL Server
DROP INDEX table_name.index_name
The DROP TABLE Statement
The DROP TABLE statement is used to delete a table.

DROP TABLE table_name
The DROP DATABASE Statement
The DROP DATABASE statement is used to delete a database.

DROP DATABASE database_name
The TRUNCATE TABLE Statement
What if we only want to delete the data inside the table, and not the table itself?

Then, use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL ALTER TABLE Syntax
ALTER TABLE table_name
ADD column_name datatype
To delete a column in a table
ALTER TABLE table_name
DROP COLUMN column_name
use ALTER TABLE to
change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
SQL ALTER TABLE Example

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 add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons
ADD DateOfBirth date
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
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
SQL AUTO INCREMENT Field
Auto-increment allows a unique number to be generated when a new record is inserted into a table.
AUTO INCREMENT a Field
CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
let the AUTO_INCREMENT sequence start with another value
ALTER TABLE Persons AUTO_INCREMENT=100
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table:
CREATE TABLE Persons
(
P_Id int PRIMARY KEY IDENTITY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
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".
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')
SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table
CREATE TABLE Persons
(
P_Id PRIMARY KEY AUTOINCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
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.
SQL CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
SQL CREATE VIEW Examples
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]
SQL Updating a View
You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
SQL Dropping a View
You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax

DROP VIEW view_name
MySQL Date Functions
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
NOW()
Returns the current date and time
CURDATE()
Returns the current date
CURTIME()
Returns the current time
DATE()
Extracts the date part of a date or date/time expression
EXTRACT()
Returns a single part of a date/time
DATE_ADD()
Adds a specified time interval to a date
DATE_SUB()
Subtracts a specified time interval from a date
DATEDIFF()
Returns the number of days between two dates
DATE_FORMAT()
Displays date/time data in different formats
GETDATE()
Returns the current date and time
DATEPART()
Returns a single part of a date/time
DATEADD()
Adds or subtracts a specified time interval from a date
DATEDIFF()
Returns the time between two dates
CONVERT()
Displays date/time data in different formats
SQL Server Date Functionsv
Function Description
GETDATE() Returns the current date and time
DATEPART() Returns a single part of a date/time
DATEADD() Adds or subtracts a specified time interval from a date
DATEDIFF() Returns the time between two dates
CONVERT() Displays date/time data in different formats
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:MM:SS
TIMESTAMP - format: YYYY-MM-DD HH:MM: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:MM:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS
TIMESTAMP - format: a unique number
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
SQL NULL Values
If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.

NULL values are treated differently from other values.

NULL is used as a placeholder for unknown or inapplicable values.
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
SQL IS NOT NULL

How do we select only the records with no NULL values in the "Address" column?
We will have to use the IS NOT NULL operator:

SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NOT NULL
ISNULL() function
MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function.
SQL Server / MS Access ISNULL()
ISNULL() returns a zero if the value is NULL:
NVL(), IFNULL(), and COALESCE() use
NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.
Microsoft Access Data Types
Text, Memo, Byte, Integer, Long, Single, Double, Currency, autoNumber, Date/Time, Yes/No, Ole Object, Hyperlink, Lookup Wizard
CHAR(size)
MySQL Data Types
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)
MySQL Data Types
Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type
TINYTEXT
MySQL Data Types
Holds a string with a maximum length of 255 characters
TEXT
MySQL Data Types
Holds a string with a maximum length of 65,535 characters
BLOB
MySQL Data Types
For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT
MySQL Data Types
For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
MEDIUMBLOB
MySQL Data Types
Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB
MySQL Data Types
For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
ENUM(x,y,z,etc.)
MySQL Data Types
Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted.
Note: The values are sorted in the order you enter them.

You enter the possible values in this format: ENUM('X','Y','Z')
SET
MySQL Data Types
Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice
TINYINT(size)
MySQL Data Types
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis
SMALLINT(size)
MySQL Data Types
-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis
MEDIUMINT(size)
MySQL Data Types
-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis
INT(size)
MySQL Data Types
-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis
BIGINT(size)
MySQL Data Types
-9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis
FLOAT(size,d)
MySQL Data Types
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)
MySQL Data Types
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)
MySQL Data Types
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
DATE()
MySQL Data Types
A date. Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME()
MySQL Data Types
*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()
MySQL Data Types
*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()
MySQL Data Types
A time. Format: HH:MM:SS
Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR()
MySQL Data Types
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
char(n)
SQL Server Data Types
Fixed-length character string. Maximum 8,000 characters
char(n)
SQL Server Data Types
Variable-length character string. Maximum 8,000 characters
varchar(max)
SQL Server Data Types
Variable-length character string. Maximum 1,073,741,824 characters
text
SQL Server Data Types
Variable-length character string. Maximum 2GB of text data
nchar(n)
SQL Server Data Types
Fixed-length Unicode data. Maximum 4,000 characters
nvarchar(n)
SQL Server Data Types
Variable-length Unicode data. Maximum 4,000 characters
nvarchar(max)
SQL Server Data Types
Variable-length Unicode data. Maximum 536,870,912 characters
ntext
SQL Server Data Types
Variable-length Unicode data. Maximum 2GB of text data
bit
SQL Server Data Types
Allows 0, 1, or NULL
binary(n)
SQL Server Data Types
Fixed-length binary data. Maximum 8,000 bytes
varbinary(n)
SQL Server Data Types
Variable-length binary data. Maximum 8,000 bytes
varbinary(max)
SQL Server Data Types
Variable-length binary data. Maximum 2GB
image
SQL Server Data Types
Variable-length binary data. Maximum 2GB
tinyint
SQL Server Data Types
Allows whole numbers from 0 to 255
smallint
SQL Server Data Types
Allows whole numbers between -32,768 and 32,767
int
SQL Server Data Types
Allows whole numbers between -2,147,483,648 and 2,147,483,647
bigint
SQL Server Data Types
Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807
decimal(p,s)
SQL Server Data Types
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
numeric(p,s)
SQL Server Data Types
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
smallmoney
SQL Server Data Types
Monetary data from -214,748.3648 to 214,748.3647
money
SQL Server Data Types
Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807
float(n)
SQL Server Data Types
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.
real
SQL Server Data Types
Floating precision number data from -3.40E + 38 to 3.40E + 38
datetime
SQL Server Data Types
From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds
datetime2
SQL Server Data Types
From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds
smalldatetime
SQL Server Data Types
From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute
date
SQL Server Data Types
Store a date only. From January 1, 0001 to December 31, 9999
time
SQL Server Data Types
Store a time only to an accuracy of 100 nanoseconds
datetimeoffset
SQL Server Data Types
The same as datetime2 with the addition of a time zone offset
timestamp
SQL Server Data Types
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
sql_variant
SQL Server Data Types
Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp
uniqueidentifier
SQL Server Data Types
Stores a globally unique identifier (GUID)
xml
SQL Server Data Types
Stores XML formatted data. Maximum 2GB
cursor
SQL Server Data Types
Stores a reference to a cursor used for database operations
table
SQL Server Data Types
Stores a result-set for later processing
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
SQL Scalar functions
SQL scalar functions return a single value, based on the input value.
AVG()
COUNT()
FIRST()
LAST()
MAX()
MIN()
SUM()
* AVG() - Returns the average value
* COUNT() - Returns the number of rows
* FIRST() - Returns the first value
* LAST() - Returns the last value
* MAX() - Returns the largest value
* MIN() - Returns the smallest value
* SUM() - Returns the sum
UCASE()
LCASE()
MID()
LEN()
ROUND()
NOW()
FORMAT()
* UCASE() - Converts a field to upper case
* LCASE() - Converts a field to lower case
* MID() - Extract characters from a text field
* LEN() - Returns the length of a text field
* ROUND() - Rounds a numeric field to the number of decimals specified
* NOW() - Returns the current system date and time
* FORMAT() - Formats how a field is to be displayed
AVG() function returns the average value of a numeric column.
SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name
SQL AVG() Example
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

SELECT AVG(OrderPrice) AS OrderAverage FROM Orders
find the customers that have an OrderPrice value higher than the average OrderPrice value
SELECT Customer FROM Orders
WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:

SELECT COUNT(column_name) FROM table_name
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name

Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.
SQL COUNT(column_name) Example
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to count the number of orders from "Customer Nilsen".

We use the following SQL statement:
SELECT COUNT(Customer) AS CustomerNilsen FROM Orders
WHERE Customer='Nilsen'

The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:
CustomerNilsen
2
SQL COUNT(*) Example
we omit the WHERE clause, like this:
SELECT COUNT(*) AS NumberOfOrders FROM Orders
SQL COUNT(DISTINCT column_name) Example
SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders
SQL FIRST() Function
SQL FIRST() Syntax
SELECT FIRST(column_name) FROM table_name
SQL LAST() Function
SQL LAST() Syntax
SELECT LAST(column_name) FROM table_name
SQL LAST() Example

O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders

Note Tip: Workaround if LAST() function is not supported:
SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1

The result-set will look like this:
LastOrderPrice
100
SQL MAX() Function
The MAX() function returns the largest value of the selected column.
SQL MAX() Syntax
SELECT MAX(column_name) FROM table_name
SQL MIN() Function
The MIN() function returns the smallest value of the selected column.
SQL MIN() Syntax
SELECT MIN(column_name) FROM table_name
SQL SUM() Function
The SUM() function returns the total sum of a numeric column.
SQL SUM() Syntax
SELECT SUM(column_name) FROM table_name
SELECT SUM(OrderPrice) AS OrderTotal FROM Orders
OrderTotal
5700
The GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
GROUP BY More Than One Column
SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders
GROUP BY Customer,OrderDate
SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
SQL HAVING Example

O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000

The result-set will look like this:
Customer SUM(OrderPrice)
Nilsen 1700
ow 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 SUM(OrderPrice)
Hansen 2000
Jensen 2000
SQL UCASE() Function
The UCASE() function converts the value of a field to uppercase.
SQL UCASE() Syntax
SELECT UCASE(column_name) FROM table_name
Syntax for SQL Server
SELECT UPPER(column_name) FROM table_name
SQL LCASE() Function
The LCASE() function converts the value of a field to lowercase.
SQL LCASE() Syntax
SELECT LCASE(column_name) FROM table_name
Syntax for SQL Server
SELECT LOWER(column_name) FROM table_name
The MID() Function
The MID() function is used to extract characters from a text field.
SQL MID() Syntax
SELECT MID(column_name,start[,length]) FROM table_name

Parameter Description
column_name Required. The field to extract characters from
start Required. Specifies the starting position (starts at 1)
length Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text
SQL MID() Example

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 extract the first four characters of the "City" column above.

We use the following SELECT statement:
SELECT MID(City,1,4) as SmallCity FROM Persons

The result-set will look like this:
SmallCity
Sand
Sand
Stav
SQL LEN() Function
The LEN() Function

The LEN() function returns the length of the value in a text field.
SQL LEN() Syntax
SELECT LEN(column_name) FROM table_name
SQL ROUND() Function
The ROUND() Function

The ROUND() function is used to round a numeric field to the number of decimals specified.
SQL ROUND() Syntax
SELECT ROUND(column_name,decimals) FROM table_name

Parameter Description
column_name Required. The field to round.
decimals Required. Specifies the number of decimals to be returned
SQL NOW() Function
The NOW() Function

The NOW() function returns the current system date and time.
SQL NOW() Syntax
SELECT NOW() FROM table_name
SQL FORMAT() Function
The FORMAT() function is used to format how a field is to be displayed.
SQL FORMAT() Syntax
SELECT FORMAT(column_name,format) FROM table_name

Parameter Description
column_name Required. The field to be formatted.
format Required. Specifies the format.
SQL FORMAT() Example

We have the following "Products" table:
Prod_Id ProductName Unit UnitPrice
1 Jarlsberg 1000 g 10.45
2 Mascarpone 1000 g 32.56
3 Gorgonzola 1000 g 15.67

Now we want to display the products and prices per today's date (with today's date displayed in the following format "YYYY-MM-DD").

We use the following SELECT statement:
SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate
FROM Products

The result-set will look like this:
ProductName UnitPrice PerDate
Jarlsberg 10.45 2008-10-07
Mascarpone 32.56 2008-10-07
Gorgonzola 15.67 2008-10-07
sp_who
shows everybody that is runnign a request on the SQL server
use of DMV
SELECT * FROM sys.dm_exec_sessions
SELECT * FROM sys.dm_exec_requests
what is DMV
dynamic management views
DBCC
Transact-SQL programming language provides DBCC statements that act as Database Console Commands for Microsoft® SQL Server™ 2000. These statements check the physical and logical consistency of a database. Many DBCC statements can fix detected problems
sys.dm_clr_loaded_assemblies
Assemblies in available in SQL Server
sys.dm_db_file_space_usage
Database file usage to determine if databases are getting low on space and need immediate attention
sys.dm_exec_cached_plans
Cached query plans available to SQL Server
sys.dm_exec_sessions
Sessions in SQL Server
sys.dm_exec_connections
Connections to SQL Server
sys.dm_db_index_usage_stats
Seeks, scans, lookups per index
sys.dm_io_virtual_file_stats
IO statistics for databases and log files
sys.dm_broker_connections
Service Broker connections to the network
sys.dm_os_memory_objects
SQL Server memory usage
sys.dm_tran_active_transactions
Transaction state for an instance of SQL Server
list of all db query
SELECT DISTINCT DB_NAME(database_id)
FROM sys.master_files