MySQL Basics Flashcards

1
Q

What does RDBMS stand for?

A

RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a field?

A

Every table is broken up into smaller entities called fields. The fields in the Customers table consist of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country. A field is a column in a table that is designed to maintain specific information about every record in the table. A column is a vertical entity in a table that contains all information associated with a specific field in a table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a record?

A

A record, also called a row, is each individual entry that exists in a table. For example, there are 91 records in the above Customers table. A record is a horizontal entity in a table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

SELECT * FROM table_name;

example:
SELECT * FROM Customers;

A

Selects all the records in the “Customers” table and shows them in a result table, called the result-set.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

SELECT column1, column2, …

FROM table_name;

A

Selects the data from table “table_name” in column1, column2,… and shows the data in a result table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

SELECT DISTINCT column1, column2, …

FROM table_name;

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

SELECT COUNT(DISTINCT column_name) FROM table_name;

example:

SELECT COUNT(DISTINCT Country) FROM Customers;

A

Lists and counts the number of different (distinct) values in the column “Country” of the table “Customers”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the WHERE clause do?

A

The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

SELECT column1, column2, …
FROM table_name
WHERE condition;

example1:

SELECT * FROM Customers
WHERE Country=’Mexico’;

example2:

A

example1:
Selects all records in the table “Customers” where the value equals “Mexico” in the column “Country”.

example2:
Selects all values in the table “Customers” where the value equals 1 in the column “CostumerID”.
SQL requires single quotes around text values. However, numeric fields should not be enclosed in quotes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which operators can be used in the WHERE clause?

A
=    Equal
>    Greater than
<    Less than
>=  Greater than or equal
<=  Less than or equal
<>  Not equal. NOTE: in some versions of SQL this operator may be written as !=
BETWEEN  Between a certain range
LIKE            Search for a pattern
IN                To specify multiple possible values for a column
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

SELECT * FROM table_name
WHERE column_name BETWEEN integer AND integer

example:

SELECT * FROM Products
WHERE Price BETWEEN 50 AND 60;

A

Lists all records of table “Products” where the values in column “Price” are between 50 and 60.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

SELECT * FROM table_name
WHERE column_name LIKE ‘,,,’;

example:

SELECT * FROM Customers
WHERE City LIKE ‘s%’;

A

Lists all records in the table “Customers” where the values in column “City” start with the character ‘s’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

SELECT * FROM table_name
WHERE column_name IN (strings, intgers,…);

example:

SELECT * FROM Customers
WHERE City IN (‘Paris’ , ‘London’);

A

Lists all records of table “Customers” where the values in column “City” are equal to “Paris” or “London”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

SELECT column1, column2, …
FROM table_name
WHERE condition1 AND condition2 AND condition3 …;

SELECT column1, column2, …
FROM table_name
WHERE condition1 OR condition2 OR condition3 …;

SELECT column1, column2, …
FROM table_name
WHERE NOT condition;

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

SELECT * FROM Customers

WHERE Country=’Germany’ AND City=’Berlin’;

A

Lists all records from table “Customers” where the value in the column “Country” is equal to “Germany” AND the value in the column “City” is equal to “Berlin”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

SELECT * FROM Customers

WHERE City=’Berlin’ OR City=’München’;

A

Lists all records in table “Costumers” where the value in column “City” equals “Berlin” OR the value in column “City” equals “München”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

SELECT * FROM Customers

WHERE NOT Country=’Germany’;

A

Lists all records of table “Customers” where the value in column “Country” is NOT equal to “Germany”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

SELECT * FROM Customers

WHERE Country=’Germany’ AND (City=’Berlin’ OR City=’München’);

A

Lists all records from table “Customers” where the value in column “Country” equals to “Germany” AND the value in column “City” equals to “Berlin” or to “München” (use parenthesis fo form complex expressions).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

SELECT * FROM Customers

WHERE NOT Country=’Germany’ AND NOT Country=’USA’;

A

Lists all records of table “Costumers” where the value in column “Country” equals NOT “Germany” and NOT “USA”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

SELECT column1, column2, …
FROM table_name
ORDER BY column1, column2, … ASC | DESC;

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

SELECT * FROM Customers

ORDER BY Country DESC, CustomerName DESC;

A

Lists all records from table “Costumers” and orders them first in descending order by the value in column “Country” and then records with the same value in “Country” are further ordered in descending order by the value in column “CostumerName”.
Numbers are first ordered then letters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

example1:

INSERT INTO table_name (column1, column2, column3, …)
VALUES (value1, value2, value3, …);

example2:

INSERT INTO table_name
VALUES (value1, value2, value3, …);

A

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:

  1. Specify both the column names and the values to be inserted.
  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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is a NULL Value?

How to test for NULL Values?

A

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!
It is not possible to test for NULL values with comparison operators, such as =, .
We will have to use the IS NULL and IS NOT NULL operators instead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

example:

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

A

Lists all records in column “CostumerName”, “ContactName” and “Address” of table “Costumers” where the value in column “Address” is empty (NULL).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;

A

Lists all records in column “CostumerName”, “ContactName” and “Address” of table “Costumers” where the value in column “Address” is NOT empty (NOT NULL).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

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

A

The UPDATE statement is used to modify the existing records in a table.
Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

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

A

This statement updates the first record (CostumerID = 1) of table “Costumers” with the new value “Alfred Schmidt” in column “ContactName” and with the new value “Frankfurt” in the column “City”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

UPDATE table_name
SET column_name1=new_value
WHERE column_name2=value;

example:

UPDATE Customers
SET ContactName=’Juan’
WHERE Country=’Mexico’;

A

This statement will update the value in column “ContactName” to “Juan” for all records where the value for column “Country” is “Mexico”.
It is the WHERE clause that determines how many records will be updated.
When you omit the WHERE clause, ALL records will be updated!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

DELETE FROM table_name WHERE condition;

example:

DELETE FROM Customers WHERE CustomerName=’Alfreds Futterkiste’;

A

The DELETE statement is used to delete existing records in a table.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!

example:
This statement deletes in table “Costumers” the value “Alfreds Futterkiste” in column “CustomerName”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

DELETE FROM table_name;

A

This statement deletes all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

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

example:

SELECT * FROM Customers
WHERE Country=’Germany’
LIMIT 3;

A

Lists from all records of table “Customers” the first 3 records where the value in column “Country” is “Germany”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

SELECT * FROM Customers

LIMIT 3;

A

Lists the first 3 records of the table “Customers”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

SELECT MIN(column_name)
FROM table_name
WHERE condition;

SELECT MAX(column_name)
FROM table_name
WHERE condition;

A
The MIN( ) function returns the smallest value of the selected column where a certain condition is met.
The MAX( ) function returns the largest value of the selected column where a certain condition is met.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q
SELECT MIN(Price) AS SmallestPrice
FROM Products;
A

Finds the smalles value of table “Products” in column “Price” and lists it in result_set (result_table) with columname “SmallestPrice”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

A

The COUNT( ) function returns the number of rows from table “table_name” that matches a specified criterion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

SELECT AVG(column_name)
FROM table_name
WHERE condition;

A

The AVG( ) function returns the average value of a numeric column where a certain condition is met.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

SELECT SUM(column_name)
FROM table_name
WHERE condition;

A

The SUM( ) function returns the total sum of a numeric column where a certian condition is met.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

SELECT * FROM table_name
WHERE column_name LIKE pattern;

  1. WHERE column_name LIKE ‘a%’
  2. WHERE column_name LIKE ‘%a’
  3. WHERE column_name LIKE ‘%or%’
  4. WHERE column_name LIKE ‘_r%’
  5. WHERE column_name LIKE ‘a_%’
  6. WHERE column_name LIKE ‘a__%’
  7. WHERE column_name LIKE ‘a%o’
  8. WHERE column_name LIKE ‘h[oa]t’
  9. WHERE column_name LIKE ‘h[^oat]t’
  10. WHERE column_name LIKE ‘c[a-b]t’
  11. WHERE column_name LIKE ‘[!bsp]%’
A

There are two wildcards often used in conjunction with the LIKE operator:
a) The percent sign (%) represents zero, one, or multiple characters
b) The underscore sign (_) represents one, single character
c) [ ] Represents any single character within the brackets
d) ^ Represents any character not in the brackets
e) - Represents any single character within the specified range
Tip: You can also combine any number of conditions using AND or OR operators.

  1. Finds any values that start with “a”
  2. Finds any values that end with “a”
  3. Finds any values that have “or” in any position
  4. Finds any values that have “r” in the second position
  5. Finds any values that start with “a” and are at least 2 characters in length
  6. Finds any values that start with “a” and are at least 3 characters in length
  7. Finds any values that start with “a” and ends with “o”
  8. h[oa]t finds hot and hat, but not hit
  9. h[^oa]t finds hit, but not hot and hat
  10. c[a-b]t finds cat and cbt
  11. Finds any value NOT starting with “b”, “s” or “p”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, …);

example:

SELECT * FROM Customers
WHERE Country IN (‘Germany’, ‘France’, ‘UK’);

A

The IN operator is a shorthand for multiple OR conditions.

Lists all records of table “Customers” where the value in column “Country” equals “Germany”, “France” or “UK”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

SELECT * FROM Customers

WHERE Country NOT IN (SELECT Country FROM Suppliers);

A

Lists all records of table “Customers” where the value in column “Country” equals NOT the value in column “Country” of table “Suppliers”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

example:

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

A

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.

Example:
Lists all records from table “Products” where the value in column “Price” is between 10 and 20.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

SELECT * FROM Products

WHERE Price NOT BETWEEN 10 AND 20;

A

Lists all records from table “Products” where the value in column “Price” is NOT between 10 and 20.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

A

Lists all records from table “Products” where the value in column “Price” is between 10 and 20 and where the value in column “CategoryID” is not 1, 2, or 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

SELECT * FROM Products
WHERE ProductName BETWEEN ‘Carnarvon Tigers’ AND ‘Mozzarella di Giovanni’
ORDER BY ProductName;

A

Lists all records from table “Products” where the value in column “ProducrName” is between “Carnarvon Tigers” AND “Mozzarella di Giovanni” and orders them in ascending alphabetic order by value in column “ProductName”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;

or:

SELECT * FROM Orders
WHERE OrderDate BETWEEN ‘1996-07-01’ AND ‘1996-07-31’;

A

Lists all records from table “Orders” where the value in column “OrderDate” is between 07/01/1996 AND 07/31/1996 or between 1996-07-01 AND 1996-07-31.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What are Aliases for?

Examples:

SELECT column_name AS alias_name
FROM table_name;

or:

SELECT column_name(s)
FROM table_name AS alias_name;
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

SELECT CustomerID AS ID, CustomerName AS Customer

FROM Customers;

A

Lists all values in column “CustomerID” of table “Customers” and displays them as “ID” and lists all values in column “CustomerName” of table “Customers” and displays them as “Customer” in the result_set.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;

A

Lists all values in column “CustomerName” of table “Customers” and displays them as “Customer” and lists all values in column “ContactName” of table “Customers” and displays them as “ContactPerson” in the result_set.
Note: It requires double quotation marks or square brackets if the alias name contains spaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

SELECT CustomerName, Address + ‘, ‘ + PostalCode + ‘ ‘ + City + ‘, ‘ + Country AS Address
FROM Customers;

A

Lists all values of column “CustomerName” of table “Customer” and concatenats all values of columns “Address”, “PostalCode”, “City” and “Country” by adding a comma + whitespace (“, “) or a whitespace (“ “) between theses values and lists them as “Address” in the result_set.

50
Q

SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName=’Around the Horn’ AND c.CustomerID=o.CustomerID;

example without aliases:

SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName=’Around the Horn’ AND Customers.CustomerID=Orders.CustomerID;

A

We use the “Customers” and “Orders” tables, and give them the table aliases of “c” and “o” respectively (to make the statement shorter). The statement lists all values of column “OrderID” and of column “OrderDate” of table “Orders” and of column “CustomerName” of table “Customers” where values of column “CustomerName” of table “Customers” equal “Around the Horn” and values of column “CustomerID” of table “Customer” equal values of column “CustomerID” of table “Orders”.

51
Q

What are the different types of SQL JOINs ?

A

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

  1. (INNER) JOIN: Returns records that have matching values in both tables
  2. LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
  3. RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table
  4. FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
52
Q

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

example:

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

A

The relationship between the two tables “Orders” and “Customers” is the “CustomerID” column, existing in both tables. This statement selects records that have matching values in column “CustomerID” in both tables and lists the values of “OrderID” from table “Orders”, of “CustomerName” from table “Customers” and of “OrderDate” from table “Orders”.

53
Q
SELECT column_name(s)
FROM ((table1
INNER JOIN table2 ON table1.column_name1 = table2.column_name1)
INNER JOIN table3 ON table1.column_name2 = table3.column_name2);

example:

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

A

The relationship between the two tables “Orders” and “Customers” is the “CustomerID” column, existing in both tables, and the relationship between the two tables “Orders” and “Shippers” is the “ShipperID” column, existing in both columns. This statement selects records that have matching values in column “CustomerID” in tables “Orders” and “Customers” and matching values in column “ShipperID” in tables “Orders” and “Shippers” and lists the values of “OrderID” from table “Orders”, of “CustomerName” from table “Customers” and of “ShipperName” from table “Shippers”.

54
Q

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

example:

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

A

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

The LEFT JOIN keyword returns all records from the left table (Customers), even if there are no matches in the right table (Orders) and displays a NULL value in these cases.

55
Q

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

example:

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

A

The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is NULL records from the left side, if there is no match.
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

56
Q
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;

A

The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right (table2) table records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
Note: The FULL OUTER 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 and the NOT matching value of the relationship column will be displayed as NULL.

57
Q

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;
A

A self join is a regular join, but the table is joined with itself.
T1 and T2 are different table aliases for the same table.

The example statement matches customers that are from the same city and lists them as “CustomerName1”, “CustomerName2” and lists the “City” in witch both are located.

58
Q

What is the UNION operator used for?

A

The UNION operator is used to combine the result-set of two or more SELECT statements and returns only the distinct values.

  1. Every SELECT statement within UNION must have the same number of columns
  2. The columns must also have similar data types
  3. 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;
59
Q

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

A

This statement returns the cities (only distinct values) from both the “Customers” and the “Suppliers” table and orders them alphabetically in ascending order.
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!
Note: The column names in the result-set are usually equal to the column names in the first SELECT statement.

60
Q
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

example:

SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

A

This statement returns the cities (duplicate values also) from both the “Customers” and the “Suppliers” table and orders them alphabetically in ascending order.
Note: The column names in the result-set are usually equal to the column names in the first SELECT statement.

61
Q
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
A

This statement returns the German cities (only distinct values) from both the “Customers” and the “Suppliers” table ordered alphabetically in ascending order.

62
Q

SELECT ‘Customer’ AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT ‘Supplier’, ContactName, City, Country
FROM Suppliers;

A

This statement lists all customers and suppliers. Notice the “AS Type” above - it is an alias. SQL Aliases are used to give a table or a column a temporary name. An alias only exists for the duration of the query. So, here we have created a temporary column named “Type”, that list whether the contact person is a “Customer” or a “Supplier”. Note: The column names in the result-set are usually equal to the column names in the first SELECT statement. That is why it is not necessary to set “Supplier” as Type in the second SELECT statement.

63
Q
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;
A

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.

Example:
This statement lists the number of customers as “Count(CustomerID)” for each country, displayed as “Country”, so the result_set has two columns.

64
Q

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

A

This statement selects columns “CustomerID” and “Country” of table “Customers” and counts the number of customers (“COUNT(CustomersID)”) which are in the same country (“GROUP BY Country”) and orders the result_set by number of customers in each country in descending order.

65
Q

SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

A

Selects the column ShipperName of table Shippers and counts the number of orders in table “Orders” (“COUNT(Orders.OrderID)”) for each shipper (“GROUP BY ShipperName”) and displays them in the result_set as “NumberOfOrders” and left joins the two tables “Orders” and “Shippers” on the related column “ShipperID” of both tables.

66
Q
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
ORDER BY COUNT(CustomerID) DESC;
A

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.

Example:
This statement selects “CustomerID” and “Country” of table “Customers” and counts the number of customers (“COUNT(CustomerID)”) in each country (“GROUP BY Country”) but displays only those resulsts where more than 5 customers were counted for one country and displays the count of customers in descending order.

67
Q

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

A

Displays the column “LastName” of table “Employees” and displays the number of counts of orders in table “Orders” (“COUNT(Orders.OrderID)”) per “LastName” of employees (“GROUP BY LastName”) as “NumberOfOrders” by making an “INNER JOIN” to table “Employees”, which searches for the matching values in column “EmployeeID” of table “Orders” and in column “EmployeeID” of table “Employees”. And displays only counts that have more than 10 orders per employee.

68
Q

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = ‘Davolio’ OR LastName = ‘Fuller’
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

A

Displays the column “LastName” of table “Employees” and displays the number of counts of orders in table “Orders” (“COUNT(Orders.OrderID)”) per “LastName” of employees (“GROUP BY LastName”) as “NumberOfOrders” by making an “INNER JOIN” to table “Employees”, which searches for the matching values in column “EmployeeID” of table “Orders” and in column “EmployeeID” of table “Employees”. On the condition that the value in column “LastName” equals to “Davolio” or “Fuller” and displays only counts that have more than 25 orders per employee. In short, it lists if employees “Davolio” or “Fuller” habe registerd more than 25 orders.

69
Q

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

A

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.
Example:
Lists the records of the column “SupplierName” of table “Suppliers” of whom the ID (SupplierID) is in both tables, “Suppliers” and “Products”, and where the value in column “Price” of table “Products” is less than 20. In short, it lists the suppliers with a product price less than 20.

70
Q
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);
A

The ANY operator allows to perform a comparison between a single column value and a range of other values. Note: The operator must be a standard comparison operator.
Example:
Llists only values of column “ProductName” of table “Products” whose ProductID is listed 10 times in table “OrderDetails”.

71
Q

SELECT ALL column_name(s)
FROM table_name
WHERE condition;

example:

SELECT ALL ProductName
FROM Products
WHERE TRUE;

A

The ALL operator:
1. returns a boolean value as a result
2. returns TRUE if ALL of the subquery values meet the condition
3. 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.
Example:
Lists all the product names.

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

The following SQL statement lists the ProductName if ALL the records in the OrderDetails table has Quantity equal to 10. This will of course return FALSE (or no record) because the Quantity column has many different values (not only the value of 10).

73
Q

example1:

SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

example2:

SELECT column1, column2, column3, …
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

A

The SELECT INTO statement copies data from one table into a new table.

Example1:
Copies all columns into a new table.

Example2:
Copies only some columns into a new table.

The new table will be created with the column-names and types as defined in the old table. You can create new column names using the AS clause.

74
Q

SELECT * INTO CustomersBackup2017

FROM Customers;

A

This statement creates a backup copy called “CustomersBackup2017” of table “Customers”.

75
Q

SELECT * INTO CustomersBackup2017 IN ‘Backup.mdb’

FROM Customers;

A

This statement uses the IN clause to copy the table “Customers” into a new table called “CustomersBackup2017” in another database called “Backup.mdb”.

76
Q

SELECT CustomerName, ContactName INTO CustomersBackup2017

FROM Customers;

A

This statement copies the columns “CustomerName” and “ContactName” of table “Customers” into a new table called “CustomersBackup2017”.

77
Q

SELECT * INTO CustomersGermany
FROM Customers
WHERE Country = ‘Germany’;

A

This statement selects only the records of table “Customers” where the value in column “Country” equals “Germany” and copies them into a new table called “CustomersGermany”.

78
Q

SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

A

This statement copies data from table “Customers” and from table “Orders” into a new table called “CustomersOrderBackup2017”.

79
Q

SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;

A

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 (WHERE 1 = 0).

80
Q

example1:

INSERT INTO table2
SELECT * FROM table1
WHERE condition;

example2:

INSERT INTO table2 (column1, column2, column3, …)
SELECT column1, column2, column3, …
FROM table1
WHERE condition;

A

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 match.
Note: The existing records in the target table are unaffected.
Example1:
Copies all columns from table1 to table2.
Example2:
Copies only some columns from table1 into table2.

81
Q

INSERT INTO Customers (CustomerName, City, Country)

SELECT SupplierName, City, Country FROM Suppliers;

A

This statement copies the values of columns “SupplierName”, “City” and “Country” of table “Suppliers” into the columns “CustomerName”, “City” and “Country” of table “Customers”. The columns in table “Customers” that are not filled with data, will contain NULL.

82
Q

INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country=’Germany’;

A

This statement copies only the values of columns “SupplierName”, “City” and “Country” of table “Suppliers” where the value in column “Country” equals “Germany” into the columns “CustomerName”, “City” and “Country” of table “Customers”. The columns in table “Customers” that are not filled with data, will contain NULL.

83
Q
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;
A

The CASE statement goes through coditions 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.

84
Q

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;

A

Lists the values of columns “OrderID” and “Quantity” of table “OrderDetails” and checks in each record whether the value in column “Quantity” is greater, equal or under 30 and displays the findings in new column “QuantitText”.

85
Q
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END);
A

Lists the values of columns “CustomerName”, “City” and “Country” of table “Customers” and checks in each record if the value in column “City” is NOT NULL, then orders the records alphabetically in ascending order of cities. If the value in column “City” is NULL then the records are ordered accordingly by countries.

86
Q

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

A

Suppose that the “UnitsOnOrder” column is optional, and may contain NULL values. Then the result of the following statement will be NULL if any of the “UnitsOnOrder” values are Null. In case of NULL values it is better to use the IFNULL() function or the COALESCE() function. Instead of NULL these functions returns 0 (with which mathematical operations are possible):

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

or

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

87
Q

What is a stored procedure?

A

A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again. 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.

CREATE PROCEDURE procedure_name
AS
sql_statement
GO;

execute a stored procedure:

EXEC procedure_name;

88
Q

CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;

execute the stored procedure “SelectAllCustomers”:

EXEC SelectAllCustomers;

A

This statement creates a stored procedure named “SelectAllCustomers” that selects all records from the “Customers” table. By writing “EXEC SelectAllCustomers” the stored procedure will be executed.

89
Q

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;

to execute stored procedure:

EXEC SelectAllCustomers @City = ‘London’, @PostalCode = ‘WA1 1DP’;

A

The first statement creates a stored procedure that selects Customers from a particular city with a particular PostalCode from the “Customers” table. The parameters @City and @PostalCode and their datatypes are separated by a comma. To execute the stored procedure the actual parameters “London” and “WA 1DP” have to be passed in the EXEC clause.

90
Q

How are not to be executed comments symbolized in SQL?

A

Single line comments start with –
Any text between – and the end of the line will be ignored (will not be executed).
Examples:
–Select all:
SELECT * FROM Customers;
SELECT * FROM Customers – WHERE City=’Berlin’;

Multi-line comments start with /* and end with /
Any text between /
and */ will be ignored:

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

Note: These comments symbols will not work in Firefox and Microsoft Edge, because Firefox and Microsoft Edge are using Microsoft Access databases!

91
Q

What are the arithmetic operators in SQL?

A
\+	Add	
-	Subtract	
*	Multiply	
/	Divide	
%	Modulo (SELECT 17 % 5; ---> Result: 2)
92
Q

What are the bitwise operators in SQL?

A

& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR

93
Q

What are the compound operators in SQL?

A
\+=	Add equals
-=	Subtract equals
*=	Multiply equals
/=	Divide equals
%=	Modulo equals
&=	Bitwise AND equals
^-=	Bitwise exclusive equals
|*=	Bitwise OR equals
94
Q

What are the logical operators in SQL?

A

ALL TRUE if all of the subquery values meet the condition
AND TRUE if all the conditions separated by AND is TRUE
ANY TRUE if any of the subquery values meet the condition
BETWEEN TRUE if the operand is within the range of comparisons
EXISTS TRUE if the subquery returns one or more records
IN TRUE if the operand is equal to one of a list of expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT TRUE
OR TRUE if any of the conditions separated by OR is TRUE
SOME TRUE if any of the subquery values meet the condition

95
Q

How to create a new database?

A

The CREATE DATABASE statement is used to create a new SQL database.
Syntax:
CREATE DATABASE databasename;

Once a database is created, you can check it in the list of databases with the following SQL command: SHOW DATABASES;

96
Q

How to delete a database?

A

The DROP DATABASE statement is used to drop an existing SQL database.
Syntax:
DROP DATABASE databasename;

Note: Be careful before dropping a database. Deleting a database will result in loss of complete information stored in the database!

97
Q

How to create a full back up of an existing SQL database?

And what is a differential back up?

A

BACKUP DATABASE databasename
TO DISK = ‘filepath’;

example:

BACKUP DATABASE testDB
TO DISK = ‘D:\backups\testDB.bak’;

The BACKUP DATABASE statement is used in SQL Server to create a full back up of an existing SQL database. Tip: Always back up the database to a different drive than the actual database. Then, if you get a disk crash, you will not lose your backup file along with the database. A differential back up only backs up the parts of the database that have changed since the last full database backup. Tip: A differential back up reduces the back up time (since only the changes are backed up). Syntax:

BACKUP DATABASE databasename
TO DISK = ‘filepath’
WITH DIFFERENTIAL;

98
Q

How to create a new table in a database?

A
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);

example:

CREATE TABLE Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255)
);

The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length for these fields is 255 characters.

99
Q

How to crate a copy from an existing table?

A

CREATE TABLE new_table_name AS
SELECT column1, column2,…
FROM existing_table_name
WHERE ….;

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.

100
Q

How to delete a table?

A

DROP TABLE table_name;

Note: Be careful before dropping a table. Deleting a table will result in loss of complete information stored in the table!

101
Q

How to delete the values inside a table but not the table itself?

A

TRUNCATE TABLE table_name;

102
Q

How to add, delete or modify columns in an existing table?

A

To add a column in a table:

ALTER TABLE table_name
ADD column_name datatype;

To delete a column in a table:

ALTER TABLE table_name
DROP COLUMN column_name;

To modify the data type of a columns in a table:

ALTER TABLE table_name
MODIFY COLUMN column_name datatype;

Note: The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

103
Q

What are constraints and how can they be applied?

A

SQL constraints are used to specify rules for data in a table. 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.

CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    column3 datatype constraint,
    ....
);
104
Q

What are the benefits of constraints and what types are commonly used in SQL?

CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    column3 datatype constraint,
    ....
);
A

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

105
Q

What is the NOT NULL constraint for?

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    Age int
);
A

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.

This statement ensures that the “ID”, “LastName”, and “FirstName” columns will NOT accept NULL values when the “Persons” table is created.

106
Q

How to create a NOT NULL constraint on a column when the table already exists?

A

ALTER TABLE table_name
MODIFY column_name NOT NULL;

example:

ALTER TABLE Persons
MODIFY Age int NOT NULL;

107
Q

What is the UNIQUE constriant for?

A

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.

108
Q
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    UNIQUE (ID)
);
A

This constraint creates a UNIQUE constraint on the “ID” column when the “Persons” table is created.

109
Q
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
A

This statement is used to name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns.

110
Q

How to create a UNIQUE constraint on a (multiple) column when the table is already created?

A
ALTER TABLE table_name
ADD UNIQUE (column_name);

example:

ALTER TABLE Persons
ADD UNIQUE (ID);

example on multiple columns:

ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

111
Q

How to drop a UNIQUE constraint?

A

ALTER TABLE table_name
DROP UNIQUE column_name;

example:

ALTER TABLE Persons
DROP UNIQUE UC_Person;

112
Q

What is a PRIMARY KEY ?

A

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

113
Q
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);
A

This statement creates a PRIMARY KEY in the “ID” column when the “Persons” table is created.

114
Q

With wich syntax can you allow naming of a PRIMARY KEY constraint, and with wich syntax can you define a PRIMARY KEY constrain on multiple columns,?

A
CREATE TABLE table_name (
    column_name1,
    column_name2,
    column_name3,
    CONSTRAINT PK_name PRIMARY KEY (column_name1, column_name2)
);

example:

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

115
Q

How to create a PRIMARY KEY constraint on a column when the table already exists? And for multiple columns when the the table already exists?

A

ALTER TABLE table_name
ADD PRIMARY KEY (colmn_name);

for multiple columns:

ALTER TABLE table_name
ADD CONSTRAINT PK_name PRIMARY KEY (column_name1,column_name2);

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

116
Q

How to delete a PRIMARY KEY constraint?

A

ALTER TABLE table_name

DROP PRIMARY KEY;

117
Q

What is a FOREIGN KEY?

A

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.

118
Q

How can you create a FOREIGN KEY on a column during the creation of a table?

A
CREATE TABLE table_name1 (
    column_name1,
    column_name2,
    column_name3,
    PRIMARY KEY (column_name1),
    FOREIGN KEY (column_name3) REFERENCES table_name2(column_name4)
);
119
Q

How to name a FOREIGN KEY constraint, and how to define a FOREIGN KEY constraint on multiple columns?

A
CREATE TABLE table_name1 (
    column_name1,
    column_name2,
    column_name3,
    PRIMARY KEY (column_name1),
    CONSTRAINT FK_name FOREIGN KEY (column_name2, column_name3)
    REFERENCES table_name2(column_name4)
);
120
Q

How to create a FOREIGN KEY constraint on a column when the table already exists? And how to name a FOREIGN KEY constraint and how to define a FOREIGN KEY constraint on multiple columns?

A

ALTER TABLE table_name1
ADD FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2);

on multiple columns:

ALTER TABLE table_name1
ADD CONSTRAINT FK_name
FOREIGN KEY (column_name1, column_name2) REFERENCES table_name2(column_name3);

121
Q

How to delete a FOREIGN KEY constraint?

A

ALTER TABLE table_name

DROP FOREIGN KEY FK_name;