DBMS Reviewer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

SQL Statements

SELECT 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.

Syntax:

• SELECT column1, column2, ...


FROM table_name;

• SELECT * FROM table_name;

SELECT DISTINCT Statement

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: SELECT DISTINCT Example:
SELECT Country FROM Customers; SELECT DISTINCT Country FROM Customers;

The following SQL statement counts and returns the number of different (distinct) countries in the
"Customers" table:
Example:
SELECT COUNT(DISTINCT Country) FROM Customers;

WHERE Clause

The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.

Syntax:

• SELECT column1, column2, ...


FROM table_name
WHERE condition;

Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
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;
Combining AND, OR, and NOT
Examples:
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city
must be "Berlin" OR "Stuttgart" (use parenthesis to form complex expressions):
SELECT * FROM Customers
WHERE Country = 'Germany' AND (City = 'Berlin' OR City = 'Stuttgart');

The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and
NOT "USA":
SELECT * FROM Customers
WHERE NOT Country = 'Germany' AND NOT Country = 'USA';

ORDER BY Keyword

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;

Examples:

SELECT * FROM Customers


ORDER BY Country;

SELECT * FROM Customers


ORDER BY Country DESC;

ORDER BY Several Columns Examples

SELECT * FROM Customers


ORDER BY Country, CustomerName;

SELECT * FROM Customers


ORDER BY Country ASC, CustomerName DESC;
INSERT INTO Statement

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:

1. Specify both the column names and the values to be inserted:

o INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

2. 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. Here, the INSERT INTO syntax would be as follows:

o INSERT INTO table_name


VALUES (value1, value2, value3, ...);

Examples:

The following SQL statement inserts a new record in the "Customers" table:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

Note: The CustomerID column is an auto-increment field and will be generated automatically when a
new record is inserted into the table.

It is also possible to only insert data in specific columns.

The following SQL statement will insert a new record, but only insert data in the "CustomerName", "City",
and "Country" columns (CustomerID will be updated automatically):

INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');
NULL Values

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.

Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value
is one that has been left blank during record creation!

To test NULL values, use IS NULL and IS NOT NULL operators.

The IS NULL operator is used to test for empty values (NULL values).

IS NULL Syntax:

• SELECT column_names
FROM table_name
WHERE column_name IS NULL;

The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).

IS NOT NULL Syntax:

• SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

Syntax:

• UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Note: If you omit the WHERE clause, all records in the table will be updated!

Examples:

Query 1:

UPDATE Customers
SET ContactName = ‘Alfred Schmidt’, City = ‘Frankfurt’
WHERE CustomerID = 1;
Query 2:

UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';

DELETE Statement

The DELETE statement is used to delete existing records in a table.

Syntax:
• DELETE FROM table_name WHERE condition;

Note: If you omit the WHERE clause, all records in the table will be deleted!

Delete All Records

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;

LIMIT Clause

The LIMIT clause is used to specify the number of records to return.

The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records
can impact performance.
Syntax:

• SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

Examples:

• selects the first three records from the "Customers" table:

SELECT * FROM Customers


LIMIT 3;

• return only 3 records, start on record 4 (OFFSET 3):

SELECT * FROM Customers


LIMIT 3 OFFSET 3;

MIN() and MAX() Functions

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;

MAX() Syntax:

• SELECT MAX(column_name)
FROM table_name
WHERE condition;

COUNT(), AVG() and SUM() Functions

The COUNT() function returns the number of rows that matches a specified criterion.

Syntax:

• SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The AVG() function returns the average value of a numeric column.

Syntax:

• SELECT AVG(column_name)
FROM table_name
WHERE condition;

The SUM() function returns the total sum of a numeric column.

Syntax:

• SELECT SUM(column_name)
FROM table_name
WHERE condition;

LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards often used in conjunction with the LIKE operator:

• The percent sign (%) represents zero, one, or multiple characters


• The underscore sign (_) represents one, single character

The percent sign and the underscore can also be used in combinations!

Syntax:

• SELECT column1, column2, ...


FROM table_name
WHERE columnN LIKE pattern;
Examples:

• selects all customers with a CustomerName starting with "a":

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';

• selects all customers with a CustomerName ending with "a":

SELECT * FROM Customers


WHERE CustomerName LIKE '%a';

• selects all customers with a CustomerName that have "or" in any position:

SELECT * FROM Customers


WHERE CustomerName LIKE '%or%';

• selects all customers with a CustomerName that have "r" in the second position:

SELECT * FROM Customers


WHERE CustomerName LIKE '_r%';

• selects all customers with a CustomerName that starts with "a" and are at least 3 characters in
length:

SELECT * FROM Customers


WHERE CustomerName LIKE 'a__%';

• selects all customers with a ContactName that starts with "a" and ends with "o":

SELECT * FROM Customers


WHERE ContactName LIKE 'a%o';

• selects all customers with a CustomerName that does NOT start with "a":

SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'a%';

Wildcard Characters

A wildcard character is used to substitute one or more characters in a string.

Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.
Example:

• selects all customers with a City starting with "ber":

SELECT * FROM Customers


WHERE City LIKE 'ber%';

• selects all customers with a City containing the pattern "es":

SELECT * FROM Customers


WHERE City LIKE '%es%';

• selects all customers with a City starting with any character, followed by "ondon":

SELECT * FROM Customers


WHERE City LIKE '_ondon';

• selects all customers with a City starting with "L", followed by any character, followed by "n",
followed by any character, followed by "on":

SELECT * FROM Customers


WHERE City LIKE 'L_n_on';

IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

Syntax:

• SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
• SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Examples:

• selects all customers that are located in "Germany", "France" or "UK":

SELECT * FROM Customers


WHERE Country IN ('Germany', 'France', 'UK');

• selects all customers that are NOT located in "Germany", "France" or "UK":

SELECT * FROM Customers


WHERE Country NOT IN ('Germany', 'France', 'UK');

• selects all customers that are from the same countries as the suppliers:

SELECT * FROM Customers


WHERE Country IN (SELECT Country FROM Suppliers);

BETWEEN Operator

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;

Examples:

• selects all products with a price between 10 and 20:

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20;

• To display the products outside the range of the previous example, use NOT BETWEEN:

SELECT * FROM Products


WHERE Price NOT BETWEEN 10 AND 20;

• selects all products with a price between 10 and 20. In addition; do not show products with a
CategoryID of 1,2, or 3:

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
• selects all products with a ProductName between "Carnarvon Tigers" and "Mozzarella di
Giovanni":

SELECT * FROM Products


WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

• selects all products with a ProductName not between "Carnarvon Tigers" and "Mozzarella di
Giovanni":

SELECT * FROM Products


WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

• selects all orders with an OrderDate between '01-July-1996' and '31-July-1996':

SELECT * FROM Orders


WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

ALIASES

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 that query.

An alias is created with the AS keyword.

Syntax:

• Column

SELECT column_name AS alias_name


FROM table_name;

• Table

SELECT column_name(s)
FROM table_name AS alias_name;

Examples:

• creates two aliases, one for the CustomerName column and one for the ContactName
column. Note: Single or double quotation marks are required if the alias name contains spaces:

SELECT CustomerName AS Customer, ContactName AS "Contact Person"


FROM Customers;
• creates an alias named "Address" that combine four columns (Address, PostalCode, City and
Country):

SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City,


Country) AS Address
FROM Customers;

JOINS

A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.

INNER JOIN

The INNER JOIN keyword selects records that have matching values in both tables.

Syntax:

• SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example:

Order Table

Customer Table

selects all orders with customer information:

SELECT Orders.OrderID, Customers.CustomerName


FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns. If there are records in the "Orders" table that do not have matches in "Customers", these
orders will not be shown!
JOIN Three (3) Tables

Example:

selects all orders with customer and shipper information:

SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName


FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

LEFT JOIN

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records (if any)
from the right table (table2).

Syntax:

• SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example:

Customer Table

Order Table

select all customers, and any orders they might have:

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).
CROSS JOIN

The CROSS JOIN keyword returns all records from both tables (table1 and table2).

Syntax:

• SELECT column_name(s)
FROM table1
CROSS JOIN table2;

Note: CROSS JOIN can potentially return very large result-sets!

Example:

Customer Table

Order Table

selects all customers, and all orders:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders;
Note: The CROSS JOIN keyword returns all matching records from both tables whether the other table
matches or not. So, if there are rows in "Customers" that do not have matches in "Orders", or if there are
rows in "Orders" that do not have matches in "Customers", those rows will be listed as well.

If you add a WHERE clause (if table1 and table2 has a relationship), the CROSS JOIN will produce the
same result as the INNER JOIN clause:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders
WHERE Customers.CustomerID=Orders.CustomerID;

SELF JOIN

A self join is a regular join, but the table is joined with itself.

Syntax:

• SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

T1 and T2 are different table aliases for the same table.

Example:

Customer Table
matches customers that are from the same city:

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;

UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.

• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order

Syntax:

• SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;

UNION ALL

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;

Note: The column names in the result-set are usually equal to the column names in the first SELECT
statement.
Example:

Customer Table

Supplier Table

• returns the cities (only distinct values) from both the "Customers" and the "Suppliers" table:

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers
ORDER BY City;

Note: If some customers or suppliers have the same city, each city will only be listed once,
because UNION selects only distinct values. Use UNION ALL to also select duplicate values!
• returns the cities (duplicate values also) from both the "Customers" and the "Suppliers" table:

SELECT City FROM Customers


UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

• returns the German cities (only distinct values) from both the "Customers" and the "Suppliers"
table:

SELECT City, Country FROM Customers


WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

• returns the German cities (duplicate values also) from both the "Customers" and the "Suppliers"
table:

SELECT City, Country FROM Customers


WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
GROUP BY Statement

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.

Syntax:

• SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot 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);

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.

Syntax:

• SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
ANY and ALL Operator

The ANY and ALL operators allow you to perform a comparison between a single column value and a
range of other values.

ANY Operator

The ANY operator:

• returns a boolean value as a result


• returns TRUE if ANY of the subquery values meet the condition

ANY means that the condition will be true if the operation is true for any of the values in the range.

Syntax:

• SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);

ALL Operator

The ALL operator:

• returns a boolean value as a result


• returns TRUE if ALL of the subquery values meet the condition
• is used with SELECT, WHERE and HAVING statements

ALL means that the condition will be true only if the operation is true for all values in the range.

Syntax:

• SELECT ALL column_name(s)


FROM table_name
WHERE condition;

• SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name
FROM table_name
WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Examples:

Product Table

OrderDetails Table

• lists the ProductName if it finds ANY records in the OrderDetails table has Quantity equal to 10
(this will return TRUE because the Quantity column has some values of 10):

SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
• lists the ProductName if ALL the records in the OrderDetails table has Quantity equal to 10. This
will of course return FALSE because the Quantity column has many different values (not only the
value of 10):

SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);

INSERT INTO SELECT Statement

The INSERT INTO SELECT statement copies data from one table and inserts it into another table.

The INSERT INTO SELECT statement requires that the data types in source and target tables matches.

Note: The existing records in the target table are unaffected.

Syntax:

• Copy all columns from one table to another table:

o INSERT INTO table2


SELECT * FROM table1
WHERE condition;

• Copy only some columns from one table into another table:

o INSERT INTO table2 (column1, column2, column3, ...)


SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
CASE Statement

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.

Syntax:

• CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

Example:

OrderDetails Table

The following SQL goes through conditions and returns a value when the first condition is met:

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;
The following SQL will order the customers by City. However, if City is NULL, then order by Country:

SELECT CustomerName, City, Country


FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);

NULL Functions

Product Table

Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.

Look at the following SELECT statement:

SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)


FROM Products;

In the example above, if any of the "UnitsOnOrder" values are NULL, the result will be NULL.

IFNULL() Function

The IFNULL() function lets you return an alternative value if an expression is NULL.

The example below returns 0 if the value is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))


FROM Products;
COALESCE() Function

SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))


FROM Products;

COMMENTS

Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.

Single Line Comments

Single line comments start with --.

Any text between -- and the end of the line will be ignored (will not be executed).

Example:

-- Select all:
SELECT * FROM Customers;

Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored.

Example:

/*Select all the columns


of all the records
in the Customers table:*/
SELECT * FROM Customers;

CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.

Syntax:

• CREATE DATABASE databasename;


DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL database.

Syntax:

• DROP DATABASE databasename;

Note: Make sure you have admin privilege before creating and dropping any database. Once a database
is created/dropped, you can check it in the list of databases with the following SQL command:

SHOW DATABASES;

CREATE TABLE Statement

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.).

Create Table Using Another Table

A copy of an existing table can also be created using CREATE TABLE.

The new table gets the same column definitions. All columns or specific columns can be selected.

If you create a new table using an existing table, the new table will be filled with the existing values from
the old table.

Syntax: Example:

• CREATE TABLE new_table_name AS


SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a database.

Syntax:

• DROP TABLE table_name;

TRUNCATE Table

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.

Syntax:

• TRUNCATE TABLE table_name;

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

Syntax: Example:

• ALTER TABLE table_name


ADD column_name datatype;

ALTER TABLE – DROP COLUMN

Syntax:

• ALTER TABLE table_name


DROP COLUMN column_name;

ALTER TABLE – MODIFY COLUMN

Syntax:

• ALTER TABLE table_name


MODIFY COLUMN column_name datatype;
CONSTRAINTS
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.

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 - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly

NOT NULL Constraint

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.
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.

Examples:

• The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:

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:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

• To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns:

ALTER TABLE Persons


ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

• To drop a UNIQUE constraint:

ALTER TABLE Persons


DROP INDEX UC_Person;
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).

Examples:

• The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

• To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns:
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).

• To create a PRIMARY KEY constraint on the "ID" column when the table is already created:
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:
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have been declared
to not contain NULL values (when the table was first created).

• To drop a PRIMARY KEY constraint:


ALTER TABLE Persons
DROP PRIMARY KEY;
FOREIGN KEY Constraint

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another
table.

The table with the foreign key is called the child table, and the table with the primary key is called the
referenced or parent table.

The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the parent table.

Example:

• The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is
created:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

• To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns:
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)
);

• To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already
created:
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:
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

• To drop a FOREIGN KEY constraint, use the following SQL:


ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
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 column it will allow 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.

Examples:

• 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:

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:

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')
);

• To create a CHECK constraint on the "Age" column when the table is already created:

ALTER TABLE Persons


ADD CHECK (Age>=18);

• To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns:

ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

• To drop a CHECK constraint

ALTER TABLE Persons


DROP CHECK CHK_PersonAge;
DEFAULT Constraint

The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.

Examples:

• The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:

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 CURRENT_DATE():

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT CURRENT_DATE()
);

• To create a DEFAULT constraint on the "City" column when the table is already created;

ALTER TABLE Persons


ALTER City SET DEFAULT 'Sandnes';

• To drop a DEFAULT constraint:

ALTER TABLE Persons


ALTER City DROP DEFAULT;
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.

Syntax:

• Creates an index on a table. Duplicate values are allowed:


o CREATE INDEX index_name
ON table_name (column1, column2, ...);

• Creates a unique index on a table. Duplicate values are not allowed:


o CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);

Examples:

• creates an index named "idx_lastname" on the "LastName" column in the "Persons" table:

CREATE INDEX idx_lastname


ON Persons (LastName);

• 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);

• The DROP INDEX statement is used to delete an index in a table.

ALTER TABLE table_name


DROP INDEX index_name;
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.

By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.

Examples:

• 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)
);

• To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:

ALTER TABLE Persons AUTO_INCREMENT=100;

• When we insert a new record into the "Persons" table, we do 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 automatically. The "FirstName" column would be set to "Lars" and the
"LastName" column would be set to "Monsen".

DATES

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

Note: The date data type are set for a column when you create a new table in your database!
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 statements and functions to a view and present the data as if the data were coming
from one single table.

A view is created with the CREATE VIEW statement.

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 view, every time a user
queries it.

Examples:

• creates a view that shows all customers from Brazil:

CREATE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

SELECT * FROM [Brazil Customers];

• creates a view that selects every product in the "Products" table with a price higher than the
average price:

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

SELECT * FROM [Products Above Average Price];


Updating a View

A view can be updated with the CREATE OR REPLACE VIEW statement.

Syntax:

• CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

Example:

adds the "City" column to the "Brazil Customers" view:

CREATE OR REPLACE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';

Dropping a View

A view is deleted with the DROP VIEW statement.

Syntax:

• DROP VIEW view_name;

Example:

The following SQL drops the "Brazil Customers" view:

DROP VIEW [Brazil Customers];


STRING Data Types

NUMERIC Data Types


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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy