Manual de SQL
Manual de SQL
(Michelle Calles)
What is SQL? Stands for structured Query Language. Lets you access and
manipulate databases.
Some of The Most Important SQL Commands
The SELECT statement is used to select data from a database. The data
returned is stored in a result table, called the result-set.
Syntax.
SELECT column1, column2, ...
FROM table_name;
If you want to select all the fields available in the table, use the following syntax:
Syntax.
SELECT * FROM table_name;
The following SQL statement selects all the columns from the
"Customers" table:
Syntax.
SELECT * FROM Customers;
SELECT DISTINCT column1, column2,…
FROM table_name;
SQL
(Michelle Calles)
The following SQL statement lists the number of different (distinct)
customer countries:
Syntax.
SELECT COUNT (DISTINCT Country)
FROM Customers;
The WHERE clause is used to filter records, clause is used to extract only
those records that fulfill a specified condition.
Syntax.
Example.
SELECT * FROM Customers
WHERE Country='Mexico';
Example.
SELECT * FROM Customers
WHERE CustomerID=1;
The
Syntax.
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3
...;
WHERE clause can be combined with AND, OR, and NOT operators. The
SQL
(Michelle Calles)
AND operator displays a record if all the conditions separated by AND are
TRUE.
Example.
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 .
..;
Example.
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
Syntax.
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Example.
SELECT * FROM Customers
WHERE NOT Country='Germany';
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
SQL
(Michelle Calles)
Example.
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
Sintax.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example.
SELECT * FROM Customers
ORDER BY Country;
Example.
SELECT * FROM Customers
ORDER BY Country DESC;
Example.
SELECT * FROM Customers
ORDER BY Country ASC;
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example.
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
SQL
(Michelle Calles)
The INSERT INTO statement is used to insert new records in a table. 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:
Syntax.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example.
If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query. However, make sure the order
of the values is in the same order as the columns in the table. The INSERT
INTO syntax would be as follows:
Syntax.
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Syntax.
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
SQL
(Michelle Calles)
Example.
Syntax.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
DELETE FROM table_name WHERE condition;
Example.
DELETE FROM Customers WHERE CustomerName='Alfreds
Futterkiste';
It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
Syntax.
DELETE FROM table_name;
SQL
(Michelle Calles)
Example.
DELETE FROM Customers;
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 on performance.
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
Syntax. (MySQL)
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Syntax. (Oracle)
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
The following SQL statement selects the first three records from the
"Customers" table:
Syntax.
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example using the
LIMIT clause:
Syntax.
SELECT * FROM Customers
The following SQL statement shows the equivalent example using
LIMIT 3;
ROWNUM:
Syntax.
SELECT * FROM Customers
WHERE ROWNUM <= 3;
SQL
(Michelle Calles)
The following SQL statement selects the first 50% of the records from the
"Customers" table:
Syntax.
SELECT TOP 50 PERCENT * FROM Customers;
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The following SQL statement shows the equivalent example using the LIMIT
clause:
Syntax.
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
Syntax.
SELECT * FROM Customers
WHERE Country='Germany' A
ND ROWNUM <= 3;
The MIN() function returns the smallest value of the selected column.
Syntax.
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Example.
SELECT MIN(Price) AS SmallestPrice
FROM Products;
SQL
(Michelle Calles)
The MAX() function returns the largest value of the selected column.
Syntax.
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example.
SELECT MAX(Price) AS LargestPrice
FROM Products;
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Example.
SELECT COUNT(ProductID)
FROM Products;
Syntax.
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example.
SELECT AVG(Price)
FROM Products;
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example.
SQL
(Michelle Calles)
Syntax.
Example.
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
Example.
SELECT * FROM Customers
WHERE City LIKE 'ber%';
Example.
SELECT * FROM Customers
WHERE City LIKE '_ondon';
SQL
(Michelle Calles)
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
Example.
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
Example.
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
Syntax.
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
Syntax. (or)
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Example.
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
SQL
(Michelle Calles)
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;
Example.
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
To display the products outside the range of the previous example, use
NOT BETWEEN:
Example.
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN with IN
Example.
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
BETWEEN Text Values
Example.
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon
Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
SQL
(Michelle Calles)
Example.
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon
Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable. An alias only exists
for the duration of the query.
Syntax. (alias column)
SELECT column_name AS alias_name
FROM table_name;
SELECT CustomerID AS ID,
CustomerName AS Customer
FROM Customers;
The following SQL statement creates two aliases, one for the
CustomerName column and one for the ContactName column. Note: It
requires double quotation marks or square brackets if the alias name
contains spaces:
Example.
SELECT CustomerName AS Customer,
ContactName AS [Contact Person]
FROM Customers;
Syntax.
Syntax
SELECT CustomerName, (alias table)
Address + ', ' + PostalCode + ' ' + City + ', ' +
Country AS Address
FROM Customers; SELECT column_name(s)
FROM table_name AS alias_name;
SQL
(Michelle Calles)
The following SQL statement selects all the orders from the customer with
CustomerID=4 (Around the Horn). We use the "Customers" and "Orders"
tables, and give them the table aliases of "c" and "o" respectively (Here we
use aliases to make the SQL shorter):
Example.
The following SQL statement is the same as above, but without aliases:
Example.
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
Example.
The INNER JOIN keyword selects records that have matching values in
both tables.
Example.
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example.
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
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.
Syntax.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SQL
(Michelle Calles)
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
Example.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table (Customers),
even if there are no matches in the right table (Orders).
The RIGHT JOIN keyword returns all records from the right table (table2),
and the matched records from the left table (table1). The result is NULL
from the left side, when there is no match.
Syntax.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Example.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Syntax.
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Example.
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;
SQL
(Michelle Calles)
The UNION operator is used to combine the result-set of two or more SELECT
statements.
Each SELECT statement within UNION must have the same number of
columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
Syntax.
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Example.
SELECT 'Customer' As Type, ContactName,
City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City,
Country
FROM Suppliers;
The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL:
Syntax.
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Example.
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
SQL
(Michelle Calles)
Example.
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
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.
Syntax.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Example.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
Example.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
SQL
(Michelle Calles)
The HAVING clause was added to SQL because the WHERE keyword could
not be used with aggregate functions.
Syntax.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Example.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
Example.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
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.
Syntax.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example.
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
SQL
(Michelle Calles)
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.
Syntax.
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
Example.
SELECT ProductName
FROM Products
WHERE ProductID
= ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
The ALL operator returns true if all of the subquery values meet the
condition.
Syntax.
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Example.
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
The SELECT INTO statement copies data from one table into a new table.
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;);
SQL
(Michelle Calles)
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Example.
SELECT * INTO CustomersBackup2017
FROM Customers;
Tip: SELECT INTO can also be used to create a new, empty table using the
schema of another. Just add a WHERE clause that causes the query to
return no data:
Example.
SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;
The INSERT INTO SELECT statement copies data from one table and inserts it
into another table.
INSERT INTO SELECT requires that data types in source and target tables
match
The existing records in the target table are unaffected
Syntax.
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Copy only some columns from one table into another table:
Syntax.
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
SQL
(Michelle Calles)
The following SQL statement copies "Suppliers" into "Customers" (fill all
columns):
Example.
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.
Syntax.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
The following SQL goes through conditions and returns a value when the
first condition is met:
Example.
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
(Michelle Calles)
The MySQL IFNULL() function lets you return an alternative value if an expression
is NULL:
Syntax.
The SQL Server ISNULL() function lets you return an alternative value when an
expression is NULL:
Syntax.
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.
Syntax.
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Example.
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
SQL
(Michelle Calles)
Syntax.
EXEC procedure_name;
Example.
EXEC SelectAllCustomers;
Example.
CREATE PROCEDURE SelectAllCustomers @City
nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City =
@City AND PostalCode = @PostalCode
GO;
Example.
--Select all:
SELECT * FROM Customers;
SQL
(Michelle Calles)
Syntax.
CREATE DATABASE testDB;
DROP DATABASE databasename;
Example.
DROP DATABASE testDB;
BACKUP DATABASE databasename
TO DISK = 'filepath';
SQL
(Michelle Calles)
A differential back up only backs up the parts of the database that have
changed since the last full database backup.
Syntax.
BACKUP DATABASE databasename
TO DISK = 'filepath'
Example.WITH DIFFERENTIAL;
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
Example.
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
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)
);
SQL
(Michelle Calles)
Syntax.
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
Example.
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
DROP TABLE table_name;
Example.
DROP TABLE Shippers;
The TRUNCATE TABLE statement is used to delete the data inside a table,
but not the table itself.
Syntax.
TRUNCATE TABLE table_name;
SQL
(Michelle Calles)
ALTER TABLE table_name
Example. ADD column_name
(Add column) datatype;
ALTER TABLE Customers
ADD Email varchar(255);
ALTER TABLE table_name
DROP COLUMN column_name datatype;
ALTER TABLE Customers
DROP COLUMN Email varchar;
To change the data type of a column in a table, use the following syntax:
Syntax. (SQL Server/ MS Access)
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Oracle.
ALTER TABLE table_name
MODIFY column_name datatype;
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
(Michelle Calles)
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.
The following constraints are commonly used in SQL:
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
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.
Syntax.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
Syntax.
ALTER TABLE Persons
MODIFY Age int NOT NULL;
SQL
(Michelle Calles)
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.
CREATE TABLE Persons (
ID
int NOT NULL UNIQUE,
LastName
varchar(255) NOT NULL,
FirstName
varchar(255),
Age int
);
Syntax. (MySQL)
CREATE TABLE Persons (
ID int NOT NULL,
LastName
varchar(255) NOT NULL,
FirstName
varchar(255),
Age int,
UNIQUE (ID)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName
varchar(255) NOT NULL,
FirstName
varchar(255),
Age int,
SQL
(Michelle Calles)
ALTER TABLE Persons
ADD UNIQUE (ID);
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
Syntax. (MySQL)
ALTER TABLE Persons
DROP INDEX UC_Person;
ALTER TABLE Persons
DROP CONSTRAINT UC_Person;
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).
Syntax. (MySQL)
CREATE TABLE Persons (
ID int NOT NULL,
LastName
varchar(255) NOT NULL,
FirstName
varchar(255),
SQL
(Michelle Calles)
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:
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: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).
SQL PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is
already created, use the following SQL:
Syntax. (MySQL / SQL Server / Oracle / MS Access)
ALTER TABLE Persons
ADD PRIMARY KEY (ID);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Syntax. (MySQL / SQL Server / Oracle / MS Access)
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
SQL
(Michelle Calles)
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:
Syntax. (MySQL)
ALTER TABLE Persons
DROP PRIMARY KEY;
ALTER TABLE Persons
DROP CONSTRAINT PK_Person;
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
SQL
(Michelle Calles)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
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)
);
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:
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
SQL
(Michelle Calles)
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.
Syntax. (MySQL)
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
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')
);
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:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;
Syntax. (MySQL)
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
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():
Syntax.
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
SQL
(Michelle Calles)
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'Sandnes';
Syntax. (Oracle)
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';
ALTER TABLE Persons
ALTER City DROP DEFAULT;
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT
Syntax.
CREATE INDEX index_name
ON table_name (column1, column2, ...);
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.
Example.
CREATE INDEX idx_lastname
ON Persons (LastName);
Example.
CREATE INDEX idx_lastname
ON Persons (LastNameFirstName);
DROP INDEX index_name ON table_name;
DROP INDEX table_name.index_name;
Syntax. (DB2/Oracle)
DROP INDEX index_name;
ALTER TABLE table_name
DROP INDEX index_name;
SQL
(Michelle Calles)
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
To let the AUTO_INCREMENT sequence start with another value, use the
following SQL statement:
Syntax. (My SQL)
ALTER TABLE Persons AUTO_INCREMENT=100;
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Syntax. (Access)
CREATE TABLE Persons (
Personid AUTOINCREMENT PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL
(Michelle Calles)
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
SQL Dates
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.
SQL Server comes with the following data types for storing a date or a
date/time value in the database:
Note: The date types are chosen for a column when you create a new table
in your database!
Syntax.
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
SQL
(Michelle Calles)
Syntax.
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example.
CREATE VIEW [Brazil Customers]
AS
SELECT CustomerName,
ContactName
FROM Customers
WHERE Country = "Brazil";
SELECT * FROM [Brazil Customers];
Updating a View. A view can be updated with the CREATE OR REPLACE VIEW
command.
Syntax.
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example.
CREATE OR REPLACE VIEW [Brazil
Customers] AS
SELECT CustomerName, ContactName,
City
FROM Customers
SQL
(Michelle Calles)
DROP VIEW view_name;
Example.
DROP VIEW [Brazil Customers];