Facebook:-https://www.facebook.com/13shtunetgmailcom Twitter:-https://twitter.com/ShambelTure E-mail:- shambelturee@gmai.com/shambelture@gmail.com :-https://www.linkedin.com/in/shambel-ture-4a6284156/ Technology Faculty Dean Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Keep in Mind That... SQL keywords are NOT case sensitive: select is the same as SELECT In this Lab we will write all SQL keywords in upper-case. Semicolon after SQL Statements? Some database systems require a semicolon at the end of each SQL statement. Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server. Some of the most important SQL commands CREATE DATABASE - creates a new database
CREATE TABLE - creates a new table
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
ALTER DATABASE - modifies a database
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
The SQL CREATE DATABASE Statement • The CREATE DATABASE statement is used to create a new SQL database. Syntax • CREATE DATABASE databasename; CREATE DATABASE Example • The following SQL statement creates a database called "testDB": Example • CREATE DATABASE testDB; The SQL 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. SELECT Syntax SELECT column1, column2, ... FROM table_name; Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all the fields available in the table, use the following syntax: SELECT * FROM table name; SELECT Column Example The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table: Example SELECT CustomerName, City FROM Customers; SQL 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. SELECT DISTINCT Syntax SELECT DISTINCT column1, column2, ... FROM table_name; SELECT Example Without DISTINCT • The following SQL statement selects ALL (including the duplicates) values from the "Country" column in the "Customers" table: Example SELECT Country FROM Customers; • The following SQL statement selects only the DISTINCT values from the "Country" column in the "Customers" table: Example SELECT DISTINCT Country FROM Customers; The SQL WHERE Clause The WHERE clause is used to filter records. The WHERE clause is used to extract only those records that fulfill a specified condition. WHERE Syntax SELECT column1, column2, ... FROM table_name WHERE condition; Note: The WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE statement, etc.! WHERE Clause Example The following SQL statement selects all the customers from the country “Adama", in the "Customers" table: Example • SELECT * FROM Customers WHERE Country=‘Adama'; Text Fields vs. Numeric Fields • SQL requires single quotes around text values (most database systems will also allow double quotes). • However, numeric fields should not be enclosed in quotes: Example SELECT * FROM Customers WHERE CustomerID=1; Create The Following Table • Customer And Orders OrderID CustomerID OrderDate Qty Country 10308 20 1996-09-18 23 New York 10309 30 1996-09-19 56 Spain 10310 50 1996-09-20 36 Poland 10311 10 1996-09-21 12 Zurick
CustomerID CustomerName ContactName Country
10 Sara Mulu Germany 20 Abebe Alem Ethiopia 30 Huseen Kedir Ethiopia 40 Zinash Asinaku USA 50 Solomon Niguse USA Operators in The WHERE Clause The following operators can be used in the WHERE clause: Operator Description SQL Statement:
= Equal SELECT * FROM Products WHERE Price = 18;
> Great than SELECT * FROM Products WHERE Price > 30; < Less than SELECT * FROM Products WHERE Price < 30; >= Great Ethan or equal SELECT * FROM Products WHERE Price >= 30; <= Less than or Equal SELECT * FROM Products WHERE Price <= 30; <> Not equal != SELECT * FROM Products WHERE Price <> 18; Between B/n a certain range SELECT * FROM Products WHERE Price BETWEEN 50 AND 60; IN To specify multiple possible SELECT * FROM Customers values for a column WHERE City IN ('Paris','London');
LIKE Search for pattern SELECT * FROM Customers
WHERE City LIKE 's%'; The SQL AND, OR and NOT Operators 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 ...; AND Example • The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin": SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; OR Syntax • SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR condition3 ...; OR Example • The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München": Example • SELECT * FROM Customers WHERE City='Berlin' OR City='München'; NOT Syntax • SELECT column1, column2, ... FROM table_name WHERE NOT condition; The following SQL statement selects all fields from "Customers" where country is NOT "Germany": Example • SELECT * FROM Customers WHERE NOT Country='Germany'; Combining AND, OR and NOT You can also combine the AND, OR and NOT operators. The following SQL statement selects all fields from "Customers" where country is "Germany" AND city must be "Berlin" OR "München" (use parenthesis to form complex expressions): Example SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München'); The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and NOT "USA": Example SELECT * FROM Customers WHERE NOT Country='Germany' AND NOT Country='USA'; The SQL 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. ORDER BY Syntax SELECT column1, column2, ... FROM table_name ORDER BY column1, column2, ... ASC|DESC; • The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column: • Example SELECT * FROM Customers ORDER BY Country; ORDER BY DESC Example • The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by the "Country" column: • Example • SELECT * FROM Customers ORDER BY Country DESC; ORDER BY Several Columns Example • The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" and the "CustomerName" column. This means that it orders by Country, but if some rows have the same Country, it orders them by CustomerName: • Example • SELECT * FROM Customers ORDER BY Country, CustomerName; ORDER BY Several Columns Example 2 • The following SQL statement selects all customers from the "Customers" table, sorted ascending by the "Country" and descending by the "CustomerName" column: Example SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC; SQL NULL Values What is a NULL Value? 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. How to Test for NULL Values? • It is not possible to test for NULL values with comparison operators, such as =, <, or <>. • We will have to use the IS NULL and IS NOT NULL operators instead. IS NULL Syntax SELECT column_names FROM table_name WHERE column_name IS NULL; The IS NULL Operator • The IS NULL operator is used to test for empty values (NULL values). • The following SQL lists all customers with a NULL value in the "Address" field: Example • SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NULL; IS NOT NULL Syntax SELECT column_names FROM table_name WHERE column_name IS NOT NULL; The IS NOT NULL Operator • The IS NOT NULL operator is used to test for non-empty values (NOT NULL values). The following SQL lists all customers with a value in the "Address" field: Example SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL; The SQL UPDATE Statement The UPDATE statement is used to modify the existing records in a table. • UPDATE Syntax • UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; • UPDATE Table • The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new city. Example UPDATE Customers SET ContactName = 'Abera', Address= ‘Adama' WHERE CustomerID = 10; UPDATE Multiple Records • It is the WHERE clause that determines how many records will be updated. • The following SQL statement will update the ContactName to “Abera" for all records where country is “Adama": Example UPDATE Customers SET ContactName=‘Abera' WHERE Country=‘Adama'; Update Warning! • Be careful when updating records. If you omit the WHERE clause, ALL records will be updated! Example • UPDATE Customers SET ContactName=‘Abera'; The SQL DELETE Statement The DELETE statement is used to delete existing records in a table. DELETE Syntax DELETE FROM table_name WHERE condition; SQL DELETE Example The following SQL statement deletes the customer “Abera" from the "Customers" table: Example DELETE FROM Customers WHERE CustomerName=Abera'; 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: DELETE FROM table_name; The following SQL statement deletes all rows in the "Customers" table, without deleting the table: Example DELETE FROM Customers; The SQL MIN() and MAX() Functions MIN() Syntax The MIN() function returns the smallest value of the selected column. SELECT MIN(column_name) FROM table_name WHERE condition; The following SQL statement finds the price of the cheapest product: Example SELECT MIN(Price) AS SmallestPrice FROM Products; The SQL MIN() and MAX() Functions MAX() Syntax The MAX() function returns the largest value of the selected column. SELECT MAX(column_name) FROM table_name WHERE condition; The following SQL statement finds the price of the cheapest product: Example SELECT MAX(Price) AS LargestPrice FROM Products; The SQL COUNT(), AVG() and SUM() Functions SQL COUNT() The COUNT() function returns the number of rows that matches a specified criterion. Count() Syntax SELECT COUNT(column_name) FROM table_name WHERE condition; The following SQL statement finds the number of products: Example SELECT COUNT(ProductID) FROM Products; The SQL COUNT(), AVG() and SUM() Functions SQL AVG() The AVG() function returns the average value of a numeric column. AVG() Syntax SELECT AVG(column_name) FROM table_name WHERE condition; The following SQL statement finds the average price of all products: Example SELECT AVG(Price) FROM Products; The SQL COUNT(), AVG() and SUM() Functions SQL SUM() The SUM() function returns the total sum of a numeric column. SUM() Syntax SELECT SUM(column_name) FROM table_name WHERE condition; The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table: Example SELECT SUM(Quantity) FROM OrderDetails; The SQL LIKE and Wildcard 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 represents a single character • LIKE Syntax • SELECT column1, column2, ... FROM table_name WHERE columnN LIKE pattern; Cont.…. • Here are some examples showing different LIKE operators with '%' and '_' wildcards: LIKE Operator Description WHERE CustomerName LIKE 'a%' Finds any values that start with "a" WHERE CustomerName LIKE '%a' Finds any values that end with "a" Finds any values that have "or" in any WHERE CustomerName LIKE '%or%' position Finds any values that have "r" in the second WHERE CustomerName LIKE '_r%' position Finds any values that start with "a" and are WHERE CustomerName LIKE 'a_%' at least 2 characters in length Finds any values that start with "a" and are WHERE CustomerName LIKE 'a__%' at least 3 characters in length Finds any values that start with "a" and WHERE ContactName LIKE 'a%o' ends with "o" SQL LIKE Examples The following SQL statement selects all customers with a CustomerName starting with "a": Example SELECT * FROM Customers WHERE CustomerName LIKE 'a%'; • The following SQL statement selects all customers with a CustomerName ending with "a": Example SELECT * FROM Customers WHERE CustomerName LIKE '%a'; The following SQL statement selects all customers with a CustomerName that have "or" in any position: Example SELECT * FROM Customers WHERE CustomerName LIKE '%or%'; • The following SQL statement selects all customers with a CustomerName that have "r" in the second position: Example • SELECT * FROM Customers WHERE CustomerName LIKE '_r%'; • The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3 characters in length: Example SELECT * FROM Customers WHERE CustomerName LIKE 'a__%'; • The following SQL statement selects all customers with a ContactName that starts with "a" and ends with "o": Example SELECT * FROM Customers WHERE ContactName LIKE 'a%o'; SQL Aliases • SQL aliases are used to give a table, or a column in a table, a temporary name. • Aliases are often used to make column names more readable. • An alias only exists for the duration of the query. Alias Column Syntax SELECT column_name AS alias_name FROM table_name; Alias Table Syntax SELECT column_name(s) FROM table_name AS alias_name; Alias for Columns Examples • The following SQL statement creates two aliases, one for the CustomerID column and one for the CustomerName column: Example • SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers; • The following SQL statement creates two aliases, one for the CustomerName column and one for the ContactName column. • Note: It requires double quotation marks or square brackets if the alias name contains spaces: Example • SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers; SQL JOIN • A JOIN clause is used to combine rows from two or more tables, based on a related column between them. • Let's look at a selection from the "Orders" table: OrderID CustomerID OrderDate Qty Country 10308 20 1996-09-18 23 New York 10309 30 1996-09-19 56 Spain 10310 50 1996-09-20 36 Poland 10311 10 1996-09-21 12 Zurick • Then, look at a selection from the "Customers" table: CustomerID CustomerName ContactName Country 10 Sara Mulu Germany 20 Abebe Alem Ethiopia 30 Huseen Kedir Ethiopia 40 Zinash Asinaku USA 50 Solomon Niguse USA • Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have matching values in both tables: Example • SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; The SQL 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. BETWEEN Syntax SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; • The following SQL statement selects all Customer with a Age BETWEEN 10 and 20: Example SELECT * FROM Customer WHERE Age BETWEEN 10 AND 20; NOT BETWEEN Example • To display the products outside the range of the previous example, use NOT BETWEEN: Example SELECT * FROM Customer WHERE Age NOT BETWEEN 10 AND 20; BETWEEN with IN Example • The following SQL statement selects all products with a price BETWEEN 10 and 20. In addition; do not show products with a CategoryID of 1,2, or 3: Example SELECT * FROM Customer WHERE Age BETWEEN 10 AND 20 AND CategoryID NOT IN (1,2,3); BETWEEN Text Values Example • The following SQL statement selects all Employee with a Emp_Name BETWEEN Abera and Alemitu: Example SELECT * FROM Employee WHERE Emp_Name BETWEEN ‘Abera' AND ‘Alemitu' ORDER BY Emp_Name; NOT BETWEEN Text Values Example The following SQL statement selects all products with a Emp_Name NOT BETWEEN Abera and Alemitu: Example SELECT * FROM Employee WHERE Emp_Name NOT BETWEEN ‘Abera' AND ‘Alemitu' ORDER BY Emp_Name; SQL 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. IN operator Syntax SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...); Or SELECT column_name(s) FROM table_name WHERE column_name IN (SELECT STATEMENT); Conti…. • The following SQL statement selects all customers that are located in "Germany", "USA“; Example SELECT * FROM Customers WHERE Country IN ('Germany', ‘USA',); • The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK": Example SELECT * FROM Customers WHERE Country NOT IN ('Germany', ‘USA',); • The following SQL statement selects all customers that are from the same countries as the Orders : Example SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Orders); SQL PRIMARY KEY Constraint SQL 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). • The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created: • MySQL Syntax: CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, PRIMARY KEY (ID) ); 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. Syntax for MySQL 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) ); Syntax for SQL Server • 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 IDENTITY(1,1) PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int ); Auto-Increment syntax INSERT INTO Persons (FirstName, LastName) VALUES (Abebe',Lami'); SQL CHECK on CREATE TABLE 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: SQL Syntax CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int CHECK (Age>=18) ); MySQL syntax CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, CHECK (Age>=18) ); SQL NOT NULL on CREATE TABLE 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. The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL values when the "Persons" table is created: Example CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255) NOT NULL, Age int ); To create a NOT NULL constraint on the "Age" column when the "Persons" table is already created, use the following SQL: ALTER TABLE Persons MODIFY Age int NOT NULL; SQL Comments • Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements. • Single line comments start with --. • Any text between -- and the end of the line will be ignored (will not be executed). • The following example uses a single-line comment as an explanation: Example --Select all: SELECT * FROM Customers; The following example uses a single-line comment to ignore the end of a line: Example SELECT * FROM Customers -- WHERE City='Berlin'; • The following example uses a single-line comment to ignore a statement: Example --SELECT * FROM Customers; SELECT * FROM Products; The SQL 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. CASE Syntax • CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN conditionN THEN resultN ELSE result END; SQL CASE Examples The following SQL goes through conditions and returns a value when the first condition is met: Example SELECT OrderID, Quantity, CASE WHEN Quantity > 30 THEN 'The quantity is greater than 30' WHEN Quantity = 30 THEN 'The quantity is 30' ELSE 'The quantity is under 30‘ END AS QuantityText FROM Orders; The following SQL will order the customers by City. However, if City is NULL, then order by Country: Example • SELECT CustomerName, City, Country FROM Customers ORDER BY (CASE WHEN City IS NULL THEN Country ELSE City END); Question Thank You For your Attention! Lab Manual two Fundamentals of Database System
Create Database Hora Bulaa Badhaadha
The SQL DROP DATABASE Statement The DROP DATABASE statement is used to drop an existing SQL database. • Syntax DROP DATABASE databasename; • The following SQL statement drops the existing database "testDB": Example • DROP DATABASE testDB; SQL BACKUP DATABASE for SQL Server • The BACKUP DATABASE statement is used in SQL Server to create a full back up of an existing SQL database. • Syntax BACKUP DATABASE databasename TO DISK = 'filepath'; • The following SQL statement creates a full back up of the existing database "testDB" to the D disk: Example BACKUP DATABASE testDB TO DISK = 'D:\backups\testDB.bak'; Or BACKUP DATABASE testDB TO DISK='D:\db_backup.BAK‘; BACKUP WITH DIFFERENTIAL Example The following SQL statement creates a differential back up of the database "testDB": • Example BACKUP DATABASE testDB TO DISK = 'D:\backups\testDB.bak' WITH DIFFERENTIAL; • Note: A differential back up reduces the back up time (since only the changes are backed up). • 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. Restore database • use testDB RESTORE DATABASE testDB FROM DISK='D:\db_backup.BAK' 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 CREATE TABLE new_table_name AS SELECT column1, column2,... FROM existing_table_name WHERE ....; Cont.…. • The following SQL creates a new table called "TestTables" (which is a copy of the "Customers" table): • Example CREATE TABLE Testable AS SELECT CustomerName, ContactName FROM customers; The SQL DROP TABLE Statement The DROP TABLE statement is used to drop an existing table in a database. Syntax DROP TABLE table_name; • The following SQL statement drops the existing table "Shippers": Example DROP TABLE Shippers; • Note: Be careful before dropping a table. Deleting a table will result in loss of complete information stored in the table! • SQL 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; SQL 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 • To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype; • The following SQL adds an "Email" column to the "Customers" table: • Example ALTER TABLE Customers ADD Email varchar(255); ALTER TABLE - DROP COLUMN • To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): ALTER TABLE table_name DROP COLUMN column_name; The following SQL deletes the "Email" column from the "Customers" table: Example ALTER TABLE Customers DROP COLUMN Email; ALTER TABLE - ALTER/MODIFY COLUMN To change the data type of a column in a table, use the following syntax: • SQL Server / MS Access: • ALTER TABLE table_name ALTER COLUMN column_name datatype; Change Data Type Example • Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table. • We use the following SQL statement: ALTER TABLE Persons ALTER COLUMN DateOfBirth year; • Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-digit format. SQL Create 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 • SQL constraints are used to specify rules for the data in a table. • Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted. • Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table. The following constraints are commonly used in SQL: • NOT NULL - Ensures that a column cannot have a NULL value • UNIQUE - Ensures that all values in a column are different • PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table • FOREIGN KEY - Uniquely identifies a row/record in another table • CHECK - Ensures that all values in a column satisfies a specific condition • DEFAULT - Sets a default value for a column when no value is specified • INDEX - Used to create and retrieve data from the database very quickly SQL FOREIGN KEY Constraint A FOREIGN KEY is a key used to link two tables together. • A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. • The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table. • The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created: • MySQL: CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) ); SQL Server / Oracle / MS Access: CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, OrderNumber int NOT NULL, PersonID int FOREIGN KEY REFERENCES Persons(PersonID) ); To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax: • MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) ); ALTER TABLE Orders ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);