DBMS Reviewer
DBMS Reviewer
DBMS Reviewer
SELECT Statement
Syntax:
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:
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
Syntax:
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.
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:
Examples:
Syntax:
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:
Examples:
The following SQL statement inserts a new record in the "Customers" table:
Note: The CustomerID column is an auto-increment field and will be generated automatically when a
new record is inserted into the table.
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):
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!
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).
• SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
UPDATE Statement
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
Syntax:
• DELETE FROM table_name WHERE condition;
Note: If you omit the WHERE clause, all records in the table will be deleted!
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:
LIMIT Clause
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:
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;
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;
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 and the underscore can also be used in combinations!
Syntax:
• selects all customers with a CustomerName that have "or" in any position:
• selects all customers with a CustomerName that have "r" in the second position:
• selects all customers with a CustomerName that starts with "a" and are at least 3 characters in
length:
• selects all customers with a ContactName that starts with "a" and ends with "o":
• selects all customers with a CustomerName that does NOT start with "a":
Wildcard Characters
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 any character, followed by "ondon":
• selects all customers with a City starting with "L", followed by any character, followed by "n",
followed by any character, followed by "on":
IN Operator
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 NOT located in "Germany", "France" or "UK":
• selects all customers that are from the same countries as the 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:
• To display the products outside the range of the previous example, use NOT BETWEEN:
• selects all products with a price between 10 and 20. In addition; do not show products with a
CategoryID of 1,2, or 3:
• selects all products with a ProductName not between "Carnarvon Tigers" and "Mozzarella di
Giovanni":
ALIASES
Syntax:
• Column
• 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:
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
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:
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
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;
Example:
Customer Table
Order Table
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:
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;
Example:
Customer Table
matches customers that are from the same 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:
UNION ALL
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
Syntax:
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:
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:
• returns the German cities (only distinct values) from both the "Customers" and the "Suppliers"
table:
• returns the German cities (duplicate values also) from both the "Customers" and the "Suppliers"
table:
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
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
ALL means that the condition will be true only if the operation is true for all values in the range.
Syntax:
• 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);
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.
Syntax:
• Copy only some columns from one table into another table:
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;
Example:
OrderDetails Table
The following SQL goes through conditions and returns a value when the first condition is met:
NULL Functions
Product Table
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.
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.
COMMENTS
Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.
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
Example:
Syntax:
Syntax:
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;
Syntax:
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.).
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:
Syntax:
TRUNCATE Table
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
Syntax:
• 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.
Syntax: Example:
Syntax:
Syntax:
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 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.
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:
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).
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);
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:
• To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns:
• To create a CHECK constraint on the "Age" column when the table is already created:
• To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns:
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:
• The DEFAULT constraint can also be used to insert system values, by using functions
like CURRENT_DATE():
• To create a DEFAULT constraint on the "City" column when the table is already created;
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:
Examples:
• creates an index named "idx_lastname" on the "LastName" column in the "Persons" table:
• create an index on a combination of columns, you can list the column names within the
parentheses, separated by commas:
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:
• To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
• 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):
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:
Note: The date data type are set for a column when you create a new table in your database!
CREATE VIEW 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.
Syntax:
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 selects every product in the "Products" table with a price higher than the
average price:
Syntax:
Example:
Dropping a View
Syntax:
Example: