Date post: | 07-Apr-2016 |
Category: |
Documents |
Upload: | asif-leghari |
View: | 222 times |
Download: | 0 times |
P H P I N T R O D U C T I O NPHP is a recursive acronym for “PHP: Hypertext Preprocessor” -- It is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
PHP is a server-side scripting language.
PHP scripts are executed on the server.
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
PHP is open source software.
PHP is free to download and use.
PHP runs on different platforms (Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP is FREE to download from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side.
Some info on MySQL which we will cover in the next workshop...
MySQL is a database server.
MySQL is ideal for both small and large applications.
MySQL supports standard SQL.
MySQL compiles on a number of platforms.
MySQL is free to download and use.
Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (like in the next slide, it outputs "Hi, I'm a PHP script!").
The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."
PHP code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was.
A visual, if you please...
Page 1 of 47
PHP Hello World:Below is the PHP source code.
It renders as HTML that looks like this:
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement.
Page 2 of 47
Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
PHP Comments:In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
P H P C O N D I T I O N SPHP Conditional Statements:
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements...
if...else statement.
Use if...else statement to execute some code if a condition is true and another code if the condition is false.
Page 3 of 47
If more than one line should be executed if a condition is true/false, the lines should be enclosed within
curly braces { }
if...elseif....else statement - use this statement to select one of several blocks of code to be executed.
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
Page 4 of 47
switch statement -
use switch statement to select one of many blocks of code to be executed.
For switches, first we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case auMohammadatically. The default statement is used if no match is found.
Page 5 of 47
if statement - use this statement to execute some code only if a specified condition is true.
The following example will output "Have a nice weekend!" if the current day is Friday:
P H P A r r a y sPage 6 of 47
An array variable is a storage area holding a number or text. The problem is, a variable will hold only one value.An array is a special variable, which can store multiple values in one single variable. An array can also contain another array as a value, which in turn can hold other arrays as well. In such a way we can create two- or three-dimensional arrays:
Example<?php// A two-dimensional array:$cars = array ( array("Volvo",100,96), array("BMW",60,59), array("Toyota",110,100) );?>
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The best solution here is to use an array.
An array can hold all your variable values under a single name. And you can access the values by referring to the array name.
Each element in the array has its own index so that it can be easily accessed.
In PHP, there are three kind of arrays:
1) Numeric array - An array with a numeric index
2) Associative array - An array where each ID key is associated with a value
3) Multidimensional array - An array containing one or more arrays
Detail is under below:
1) Numeric array:
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
In the following example the index is auMohammadatically assigned (the index starts at 0):
Page 7 of 47
In the following example we assign the index manually:
In the following example you access the variable values by referring to the array name and index:
The code above will output:
2) Associative array:
With an associative array, each ID key is associated with a value.When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them.In this example we use an array to assign ages to the different persons:
This example is the same as the one above, but shows a different way of creating the array:
Page 8 of 47
3) Multidimensional array:
In a multidimensional array, each element in the main array can also be an array.And each element in the sub-array can be an array, and so on.
Example1:In this example we create a multidimensional array, with auMohammadatically assigned ID keys:
$families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
The array above would look like this if written to the output:
Array([Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan )[Quagmire] => Array ( [0] => Glenn
Page 9 of 47
)[Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior )
)
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
The code above will output:
Is Megan a part of the Griffin family?
These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.
Installation:
There is no installation needed to use these functions; they are part of the PHP core.
Runtime Configuration:
This extension has no configuration directives defined in php.ini.
PHP Array Constants:Constant Description
CASE_LOWER Used with array_change_key_case() to convert array keys to lower case
CASE_UPPER Used with array_change_key_case() to convert array keys to upper case
SORT_ASC Used with array_multisort() to sort in ascending order
SORT_DESC Used with array_multisort() to sort in descending order
SORT_REGULAR Used to compare items normally
SORT_NUMERIC Used to compare items numerically
SORT_STRING Used to compare items as strings
SORT_LOCALE_STRING Used to compare items as strings, based on the current locale
PHP Date and Time Functions
These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.
Installation:
There is no installation needed to use these functions; they are part of the PHP core.
Runtime Configuration
The behavior of the these functions is affected by settings in php.ini. All these parameters are available in PHP version 5 and onwards.
Date/Time configuration options:
Page 10 of 47
Name Default Description Changeable
date.default_latitude "31.7667" Specifies the default latitude. PHP_INI_ALL
date.default_longitude "35.2333" Specifies the default longitude PHP_INI_ALL
date.sunrise_zenith "90.83" Specifies the default sunrise zenith PHP_INI_ALL
date.sunset_zenith "90.83" Specifies the default sunset zenith PHP_INI_ALL
date.timezone "" Specifies the default timezone PHP_INI_ALL
Function Description PHP
checkdate() Validates a Gregorian date 3
date_create() Returns new DateTime object 5
date_date_set() Sets the date 5
date_default_timezone_get() Returns the default time zone 5
date_default_timezone_set() Sets the default time zone 5
date_format() Returns date formatted according to given format 5
date_isodate_set() Sets the ISO date 5
date_modify() Alters the timestamp 5
date_offset_get() Returns the daylight saving time offset 5
date_parse() Returns associative array with detailed info about given date
5
date_sun_info() Returns an array with information about sunset/sunrise and twilight begin/end.
5
date_sunrise() Returns the time of sunrise for a given day / location 5
date_sunset() Returns the time of sunset for a given day / location 5
date_time_set() Sets the time 5
date_timezone_get() Return time zone relative to given DateTime 5
date_timezone_set() Sets the time zone for the DateTime object 5
date() Formats a local time/date 3
getdate() Returns an array that contains date and time information for a Unix timestamp
3
gettimeofday() Returns an array that contains current time information
3
gmdate() Formats a GMT/UTC date/time 3
gmmktime() Returns the Unix timestamp for a GMT date 3
gmstrftime() Formats a GMT/UTC time/date according to locale settings
3
idate() Formats a local time/date as integer 5
localtime() Returns an array that contains the time components of a Unix timestamp
4
microtime() Returns the microseconds for the current time 3
mktime() Returns the Unix timestamp for a date 3
strftime() Formats a local time/date according to locale settings
3
strptime() Parses a time/date generated with strftime() 5
strtotime() Parses an English textual date or time into a Unix timestamp
3
time() Returns the current time as a Unix timestamp 3
timezone_abbreviations_list() Returns associative array containing dst, offset and the timezone name
5
timezone_identifiers_list() Returns numerically index array with all timezone identifiers
5
Page 11 of 47
timezone_name_from_abbr() Returns the timezone name from abbrevation 5
timezone_name_get() Returns the name of the timezone 5
timezone_offset_get() Returns the timezone offset from GMT 5
timezone_open() Returns new DateTimeZone object 5
timezone_transitions_get() Returns all transitions for the timezone 5
PHP Date / Time Constants:Constant Description
DATE_AMOHAMMAD AMohammad (example: 2005-08-15T16:13:03+0000)
DATE_COOKIE HTTP Cookies (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_ISO8601 ISO-8601 (example: 2005-08-14T16:13:03+0000)
DATE_RFC822 RFC 822 (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_RFC850 RFC 850 (example: Sunday, 14-Aug-05 16:13:03 UTC)
DATE_RFC1036 RFC 1036 (example: Sunday, 14-Aug-05 16:13:03 UTC)
DATE_RFC1123 RFC 1123 (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_RFC2822 RFC 2822 (Sun, 14 Aug 2005 16:13:03 +0000)
P H P L o o p sOften when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.In PHP, we have the following looping statements:
1. while - loops through a block of code while a specified condition is true.
Page 12 of 47
The while loop executes a block of code while a condition is true. The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
2. do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true.
The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.The next example defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5.
Page 13 of 47
3. for - loops through a block of code a specified number of times.
Parameters: init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
Page 14 of 47
increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop) .The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
4. foreach -Loops through a block of code for each element in an array.
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
The following example demonstrates a loop that will print the values of the given array:
Page 15 of 47
Winner of the most impressive slide award.
P H P F U N C T I O N SWe will now explore how to create your own functions.
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
A function will be executed by a call to the function.
Page 16 of 47
Give the function a name that reflects what the function does. The function name can start with a letter or underscore (not a number).
A simple function that writes a name when it is called:
Parameters:Adding parameters...
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
Page 17 of 47
This example adds different punctuation.
P H P F o r m s - $ _ G E T F u n c t i o n
The built-in $_GET function is used to collect values from a form sent with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max. 100 characters).
Page 18 of 47
Notice how the URL carries the information after the file name.
The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will auMohammadatically be the keys in the $_GET array).
When using method="get" in HTML forms, all variable names and values are displayed in the URL.
This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
The get method is not suitable for large variable values; the value cannot exceed 100 chars.
P H P F o r m s - $ _ P O S T F u n c t i o nThe built-in $_POST function is used to collect values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
Page 19 of 47
And here is what the code of action.php might look like:
Apart from htmlspecialchars() and (int), it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page.
For the age field, since we know it is a number, we can just convert it to an integer which will auMohammadatically get rid of any stray characters. The $_POST['name'] and $_POST['age'] variables are auMohammadatically set for you by PHP.
When to use method="post"?
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
M y S Q L O p e r a t o r sMySQL Operators Allowed in the WHERE Clause
With the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
Page 20 of 47
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the columns
Note: In some versions of SQL the <> operator may be written as !=
The AND & OR OperatorsThe AND operator displays a record if both the first condition and the second condition is true.
The OR operator displays a record if either the first condition or the second condition is true.
AND Operator ExampleThe "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
Now we want to select only the persons with the first name equal to "Aslam" AND the last name equal to "Ali":
We use the following SELECT statement:
SELECT * FROM PersonsWHERE FirstName='Aslam'AND LastName='Ali'
The result-set will look like this:
P_Id LastName FirstName Address City
2 Ali Aslam Tounsa Mor Kot Addu
OR Operator ExampleNow we want to select only the persons with the first name equal to "Aslam" OR the first name equal to "Asif":
We use the following SELECT statement:
SELECT * FROM PersonsWHERE FirstName='Aslam'OR FirstName='Asif'
The result-set will look like this:
Page 21 of 47
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
Combining AND & ORYou can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only the persons with the last name equal to "Ali" AND the first name equal to "Aslam" OR to "Asif":
We use the following SELECT statement:
SELECT * FROM Persons WHERELastName='Ali'AND (FirstName='Aslam' OR FirstName='Asif')
The result-set will look like this:
P_Id LastName FirstName Address City
2 Ali Aslam Tounsa Mor Kot Addu
The ORDER BY KeywordThe ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY SyntaxSELECT column_name(s)FROM table_nameORDER BY column_name(s) ASC|DESC
ORDER BY Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Mohammad Ward No. 04 D.D.Pannah
Now we want to select all the persons from the table above, however, we want to sort the persons by their last name.
Page 22 of 47
We use the following SELECT statement:
SELECT * FROM PersonsORDER BY LastName
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
4 Tahir Mohammad Ward No. 04 D.D.Pannah
3 Sajjad Arib Ward No. 06 D.D.Pannah
2 Ali Aslam Tounsa Mor Kot Addu
ORDER BY DESC ExampleNow we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.
We use the following SELECT statement:
SELECT * FROM PersonsORDER BY LastName DESC
The result-set will look like this:
P_Id LastName FirstName Address City
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Mohammad Ward No. 04 D.D.Pannah
1 Khan Asif Pattal Mor Kot Addu
The INSERT INTO StatementThe INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_nameVALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
Page 23 of 47
INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)
SQL INSERT INTO ExampleWe have the following "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
Now we want to insert a new row in the "Persons" table.
We use the following SQL statement:
INSERT INTO PersonsVALUES (4,'Tahir', 'Hussain', 'Near Bus Stop', 'D.D.Pannah')
The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Hussain Near Bus Stop D.D.Pannah
Insert Data Only in Specified ColumnsIt is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the "FirstName" columns:
INSERT INTO Persons (P_Id, LastName, FirstName)VALUES (5, 'Imran', 'Usama')
The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Hussain Bus Stop D.D.Pannah
5 Imran Usama
The UPDATE StatementPage 24 of 47
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_nameSET column1=value, column2=value2,...WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
SQL UPDATE ExampleThe "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Hussain Bus Stop D.D.Pannah
5 Imran Usama
Now we want to update the person "Imran, Usama" in the "Persons" table.
We use the following SQL statement:
UPDATE PersonsSET Address='Ward No. 6', City='Kot Addu'WHERE LastName='Imran' AND FirstName='Usama'
The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu2 Ali Aslam Tounsa Mor Kot Addu3 Sajjad Arib Ward No. 06 D.D.Pannah4 Tahir Hussain Bus Stop D.D.Pannah
5 Imran Usama Ward No. 6 Kot Addu
SQL UPDATE WarningBe careful when updating records. If we had omitted the WHERE clause in the example above, like this:
UPDATE PersonsSET Address='Ward No. 6', City='Kot Addu'
The "Persons" table would have looked like this:
P_Id LastName FirstName Address City
1 Khan Asif Ward No. 6 Kot Addu
2 Ali Aslam Ward No. 6 Kot Addu
3 Sajjad Arib Ward No. 6 Kot Addu
Page 25 of 47
4 Tahir Hussain Ward No. 6 Kot Addu
5 Imran Usama Ward No. 6 Kot Addu
The DELETE StatementThe DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_nameWHERE some_column=some_value
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
SQL DELETE ExampleThe "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Hussain Bus Stop D.D.Pannah
5 Imran Usama Ward No. 6 Kot Addu
Now we want to delete the person "Imran, Usama" in the "Persons" table.
We use the following SQL statement:
DELETE FROM PersonsWHERE LastName='Imran' AND FirstName='Usama'
The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Hussain Bus Stop D.D.Pannah
Delete All Rows
Page 26 of 47
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
or
DELETE * FROM table_name
Note: Be very careful when deleting records. You cannot undo this statement!
The TOP ClauseThe TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance.
Note: Not all database systems support the TOP clause.
SQL Server Syntax
SELECT TOP number|percentcolumn_name(s)FROM table_name
SQL SELECT TOP Equivalent in MySQL and OracleMySQL Syntax
SELECT column_name(s)FROM table_nameLIMIT number
Example
SELECT *FROM PersonsLIMIT 5
Oracle Syntax
SELECT column_name(s)FROM table_nameWHERE ROWNUM <= number
Example
SELECT *FROM PersonsWHERE ROWNUM <=5
SQL TOP ExampleThe "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Mohammad Ward No. 04 D.D.Pannah
Page 27 of 47
Now we want to select only the two first records in the table above.
We use the following SELECT statement:
SELECT TOP 2 * FROM Persons
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
SQL TOP PERCENT ExampleThe "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
4 Tahir Mohammad Ward No. 04 D.D.Pannah
Now we want to select only 50% of the records in the table above.
We use the following SELECT statement:
SELECT TOP 50 PERCENT * FROM Persons
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
LIKE OperatorThe LIKE operator is used to search for a specified pattern in a column.
SQL LIKE Syntax
SELECT column_name(s)FROM table_nameWHERE column_name LIKE pattern
LIKE Operator ExampleThe "Persons" table:
Page 28 of 47
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
Now we want to select the persons living in a city that starts with "K" from the table above.
We use the following SELECT statement:
SELECT * FROM PersonsWHERECityLIKE 'K%'
The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
Next, we want to select the persons living in a city that ends with an "u" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM PersonsWHERECity LIKE '%u'
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
Next, we want to select the persons living in a city that contains the pattern "nah" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons
WHERECity LIKE '%nah%'
The result-set will look like this:
P_Id LastName FirstName Address City
3 Sajjad Arib Ward No. 06 D.D.Pannah
It is also possible to select the persons living in a city that does NOT contain the pattern "nah" from the "Persons" table, by using the NOT keyword.
We use the following SELECT statement:
SELECT * FROM PersonsWHERECity NOT LIKE '%nah%'
Page 29 of 47
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
The IN OperatorThe IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)FROM table_nameWHERE column_name IN (value1,value2,...)
IN Operator ExampleThe "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
Now we want to select the persons with a last name equal to "Khan" or "Sajjad" from the table above.
We use the following SELECT statement:
SELECT * FROM PersonsWHERE LastName IN ('Khan','Sajjad')
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
The BETWEEN OperatorThe BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.
SQL BETWEEN Syntax
SELECT column_name(s)FROM table_nameWHERE column_nameBETWEEN value1 AND value2
BETWEEN Operator Example
Page 30 of 47
The "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
Now we want to select the persons with a last name alphabetically between "Khan" and "Sajjad" from the table above.
We use the following SELECT statement:
SELECT * FROM PersonsWHERE LastNameBETWEEN 'Khan' AND 'Sajjad'
The result-set will look like this:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
Note: The BETWEEN operator is treated differently in different databases!
In some databases, persons with the LastName of "Khan" or "Sajjad" will not be listed, because the BETWEEN operator only selects fields that are between and excluding the test values.
In other databases, persons with the LastName of "Khan" or "Sajjad" will be listed, because the BETWEEN operator selects fields that are between and including the test values.
And in other databases, persons with the LastName of "Khan" will be listed, but "Sajjad" will not be listed (like the example above), because the BETWEEN operator selects fields between the test values, including the first test value and excluding the last test value.
Therefore: Check how your database treats the BETWEEN operator.
Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:
SELECT * FROM PersonsWHERE LastNameNOT BETWEEN 'Khan' AND 'Sajjad'
The result-set will look like this:
P_Id LastName FirstName Address City
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
SQL AliasYou can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.
An alias name could be anything, but usually it is short.
Page 31 of 47
SQL Alias Syntax for Tables
SELECT column_name(s)FROM table_nameAS alias_name
SQL Alias Syntax for Columns
SELECT column_name AS alias_nameFROM table_name
Alias ExampleAssume we have a table called "Persons" and another table called "Product_Orders". We will give the table aliases of "p" and "po" respectively.
Now we want to list all the orders that "Asif Khan" is responsible for.
We use the following SELECT statement:
SELECT po.OrderID, p.LastName, p.FirstNameFROM Persons AS p,Product_Orders AS poWHERE p.LastName='Khan' AND p.FirstName='Asif'
The same SELECT statement without aliases:
SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstNameFROM Persons,Product_OrdersWHERE Persons.LastName='Khan' AND Persons.FirstName='Asif'
As you'll see from the two SELECT statements above; aliases can make queries easier to both write and to read.
S Q L P R I M A R Y K E YDescription:
The SQL PRIMARY KEY is a column in a table which must contain a unique value which can be used to identify each and every row of a table uniquely.
However, SQL supports primary keys directly with the PRIMARY KEY constraint.
Functionally, it is the same as the UNIQUE constraint, except that only one PRIMARY KEY can be defined for a given table. PRIMARY KEY's will not allow NULL values.
A primary key is used to identify each row identically in a table. It may be a part of the actual record itself.
The SQL PRIMARY KEY can be made up by one or more fields on a table and when it happens, they are called a composite key.
Primary keys can be specified at the time of CREATING TABLE or the time of changing the structure of the existing table using ALTER TABLE statement.
Page 32 of 47
This constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. This constraint ensures that the specific column or combination of two or more columns for a table have an unique identity which helps to find a particular record in a table more easily and quickly.
Syntax:CREATE TABLE <table_name>
column1 data_type[(size)] NOT NULL PRIMARY KEY,
column2 data_type[(size)],
...);
Paramaters:Name Description
table_name Name of the table where data is stored.
column1,column2 Name of the columns of a table.
data_type Is char, varchar, integer, decimal, date and more.
size Maximum length of the column of a table.
Examples:
Suppose, we are going to create a table named 'agent1'. It contain the columns and data types which shown bellow. For each row of 'agent1' table, it is required to identify each agent with a unique code, because the name of two or more agents of a city of a country may be same.
So, it is not a good choice to create PRIMARY KEY on 'agent_name'. The 'agent_code' could be
the only and exclusive choice for a PRIMARY KEY for this table.
Field NameData Type Size Decimal Places NULL Constraint
agent_code char 6 No PRIMARY KEY
agent_name char 40 No
working_area char 35 Yes
commission decimal 10 2 Yes
phone_no char 17 Yes
The following sql statement can be used :1. CREATE TABLE agent1( 2. agent_code char(6) NOT NULL PRIMARY KEY, 3. agent_name char(40) NOT NULL, 4. working_area char(35), 5. commission decimal(10,2), 6. phone_no char(17) 7. ) ;
S Q L J O I NThe JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
Page 33 of 47
A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.
Look at the "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.
Next, we have the "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to the persons in the "Persons" table without using their names.
Notice that the relationship between the two tables above is the "P_Id" column.
Different SQL JOINsBefore we continue with examples, we will list the types of JOIN you can use, and the differences between them.
JOIN: Return rows when there is at least one match in both tables. LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table.
FULL JOIN: Return rows when there is a match in one of the tables.
SQL INNER JOIN KeywordThe INNER JOIN keyword return rows when there is at least one match in both tables.
SQL INNER JOIN Syntax
SELECT column_name(s)FROM table_name1INNER JOIN table_name2ON table_name1.column_name=table_name2.column_name
Page 34 of 47
PS: INNER JOIN is the same as JOIN.
SQL INNER JOIN Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
The "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons with any orders.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsINNER JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Khan Asif 22456
Khan Asif 24562
Sajjad Arib 77895
Sajjad Arib 44678
The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in "Persons" that do not have matches in "Orders", those rows will NOT be listed.
SQL LEFT JOIN KeywordThe LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).
SQL LEFT JOIN Syntax
SELECT column_name(s)FROM table_name1
Page 35 of 47
LEFT JOIN table_name2ON table_name1.column_name=table_name2.column_name
PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.
SQL LEFT JOIN Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
The "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders - if any, from the tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsLEFT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Khan Asif 22456
Khan Asif 24562
Sajjad Arib 77895
Sajjad Arib 44678
Ali Aslam
The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in the right table (Orders).
SQL RIGHT JOIN KeywordThe RIGHT JOIN keyword returns all the rows from the right table (table_name2), even if there are no matches in the left table (table_name1).
Page 36 of 47
SQL RIGHT JOIN Syntax
SELECT column_name(s)FROM table_name1RIGHT JOIN table_name2ON table_name1.column_name=table_name2.column_name
PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
SQL RIGHT JOIN Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
The "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the orders with containing persons - if any, from the tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsRIGHT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Khan Asif 22456
Khan Asif 24562
Sajjad Arib 77895
Sajjad Arib 44678
34764
The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches in the left table (Persons).
SQL FULL JOIN Keyword
Page 37 of 47
The FULL JOIN keyword return rows when there is a match in one of the tables.
SQL FULL JOIN Syntax
SELECT column_name(s)FROM table_name1FULL JOIN table_name2ON table_name1.column_name=table_name2.column_name
SQL FULL JOIN Example
The "Persons" table:
P_Id LastName FirstName Address City
1 Khan Asif Pattal Mor Kot Addu
2 Ali Aslam Tounsa Mor Kot Addu
3 Sajjad Arib Ward No. 06 D.D.Pannah
The "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders, and all the orders with their persons.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsFULL JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Khan Asif 22456
Khan Asif 24562
Sajjad Arib 77895
Sajjad Arib 44678
Ali Aslam
34764
Page 38 of 47
The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Persons", those rows will be listed as well.
The SQL UNION OperatorThe UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1UNION ALLSELECT column_name(s) FROM table_name2
PS: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.
SQL UNION Example:Look at the following tables:
"Employees_Norway":
E_ID E_Name
01 Khan, Asif
02 Ali, Aslam
03 Ali, Stephen
04 Sajjad, Arib
"Employees_USA":
E_ID E_Name
01 Turner, Sally
02 Kent, Clark
03 Ali, Stephen
04 Scott, Stephen
Now we want to list all the different employees in Norway and USA.
We use the following SELECT statement:
SELECT E_Name FROM Employees_NorwayUNIONSELECT E_Name FROM Employees_USA
The result-set will look like this:
Page 39 of 47
E_Name
Khan, Asif
Ali, Aslam
Ali, Stephen
Sajjad, Arib
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.
SQL UNION ALL ExampleNow we want to list all employees in Norway and USA:
SELECT E_Name FROM Employees_NorwayUNION ALLSELECT E_Name FROM Employees_USA
S Q L F O R E I G N K E Y
DescriptionThe SQL FOREIGN KEY CONSTRAINT is used to ensure the referential integrity of the data in one table to match values in another table.
The FOREIGN KEY CONSTRAINT is a column or list of columns which points to the PRIMARY KEY of another table.
The main purpose of FOREIGN KEY is, only those values will appear which are present in the primary key table.For each row in the referencing table( the table contains the FOREIGN KEY), the foreign key must match an existing primary key in the referenced table(the table contains the PRIMARY KEY). This enforcement of FOREIGN KEY called the Referential Integrity.
The structure and data type of PRIMARY KEY and FOREIGN KEY must be same.
The values of the FOREIGN KEY columns in each row of the referencing table have to match with the values of the corresponding primary key columns of a row in the referenced table.
SyntaxCREATE TABLE <table_name>(
column1 data_type[(size)] ,
column2 data_type[(size)] , constraint(constraint_name)
Page 40 of 47
FOREIGN KEY [column1,column2...] REFERENCES
[primary_key_table] (column_list_of_primary_key_table)
...);
ParametersName Description
table_name The name of the table where data is stored.
column1,column2 Name of the columns of a table.
data_type Is char, varchar, integer, decimal, date and more.
size Maximum length of the column of a table.
constraint Is a key word. This key word is optional.
constraint_name Is a constraint name defined by user.
primary_key_table Table where primary key resides.
column_list_of_primary_key_table List of columns which makes primary key for a table.
ExampleSuppose, we have a table 'agents', that includes all agents data, and we are going to create another table named 'customer1', that includes all customers records. The columns and data types for both the tables have shown bellow.
The constraint here is that all customers must be associated with an agent that is already in the 'agents' table. In this case, an SQL FOREIGN KEY CONSTRAINT should be created with the 'customer1' table which is related to the SQL PRIMARY KEY CONSTRAINT of the 'agents' table.
Now, we can ensure that all customers in the 'customer1' table are related to an agent in the 'agents' table. In other words, the 'customer1' table can not contain information of any agent who is not in the 'agents' table.
agents
Field Name Data Type Size Decimal Places NULL Constraint
agent_code char 6 No PRIMARY KEY
agent_name char 40 No
working_area char 35 Yes
commission decimal 10 2 Yes
phone_no char 17 Yes
customer1
Field Name Data Type Size Decimal Places NULL Constraint
cust_code char 6 No PRIMARY KEY
cust_name char 25 Yes
cust_city char 25 Yes
agent_code char 6 Yes FOREIGN KEY
The following sql statement can be used :
1. CREATE TABLE customer1(
Page 41 of 47
2. cust_code char(6) NOT NULL PRIMARY KEY,
3. cust_name char(25),
4. cust_city char(25),
5. agent_code char(6),
6. FOREIGN KEY(agent_code)
7. REFERENCES agents (agent_code)
8. ) ;
Pictorial representation
The created table can be populated with data using INSERT INTO statement.
Example for usage of Primary Key and Foreign Key:
سب سے پہلے ہم (table1) اور testکے نام سے دو عدد ٹیبلز بناتے ہیں۔
First, we make two tables namely table1 and test.
Table structure for table table1
CREATE TABLE IF NOT EXISTS `table1`(`c1` int(11) NOT NULL AUTO_INCREMENT,
`c2` int(11) NOT NULL, `c3` int(11) NOT NULL, PRIMARY KEY (`c1`))
ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
-- Dumping data for table `table1`
INSERT INTO `table1` (`c1`, `c2`, `c3`) VALUES
(1, 1, 32),(2, 2, 232);
Table structure for table test
CREATE TABLE IF NOT EXISTS `test`( `id` int(11) NOT NULL AUTO_INCREMENT, `name`
varchar(100) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT
CHARSET=latin1 AUTO_INCREMENT=3 ;
-- Dumping data for table `test`
INSERT INTO `test` (`id`, `name`) VALUES
(1, 'name one'), (2, 'name two');
Now run this query and check the relation........
Page 42 of 47
SELECT `table1`.`c1`,`table1`.`c2`,`table1`.`c3`,`test`.`id`,`test`.`name`
FROM `table1`
LEFT OUTER JOIN `test` ON (`table1`.`c2` = `test`.`id`)
Result will look like this
c1 c2 c3 id name
1 1 32 1 name one
2 2 232 2 name two
**use foriegn key as varchar instead of int**CREATE TABLE a(rno VARCHAR( 2 ) PRIMARY KEY ,deptno VARCHAR( 2 ))
create table b (rno varchar(2), name varchar(20), constraint abcxyz foreign key(rno) references a(rno))
S Q L C o n s t r a i n t sConstraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).
We will focus on the following constraints:
• NOT NULL • UNIQUE • PRIMARY KEY • FOREIGN KEY • CHECK • DEFAULT
SQL NOT NULL ConstraintThe NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values:
CREATE TABLE Persons
(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))SQL UNIQUE Constraint
Page 43 of 47
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
________________________________________
SQL UNIQUE Constraint on CREATE TABLEThe following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:MySQL:CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),UNIQUE (P_Id))SQL Server / Oracle / MS Access:CREATE TABLE Persons(P_Id int NOT NULL UNIQUE,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:MySQL / SQL Server / Oracle / MS Access:CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName))
________________________________________SQL UNIQUE Constraint on ALTER TABLETo create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following SQL:MySQL / SQL Server / Oracle / MS Access:ALTER TABLE PersonsADD UNIQUE (P_Id)To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:MySQL / SQL Server / Oracle / MS Access:ALTER TABLE PersonsADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
________________________________________To DROP a UNIQUE ConstraintTo drop a UNIQUE constraint, use the following SQL:MySQL:ALTER TABLE PersonsDROP INDEX uc_PersonIDSQL Server / Oracle / MS Access:ALTER TABLE PersonsDROP CONSTRAINT uc_PersonID
SQL PRIMARY KEY ConstraintThe PRIMARY KEY constraint uniquely identifies each record in a database table.Primary keys must contain unique values.A primary key column cannot contain NULL values.Each table should have a primary key, and each table can have only ONE primary key.________________________________________SQL PRIMARY KEY Constraint on CREATE TABLEThe following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:MySQL:CREATE TABLE Persons(P_Id int NOT NULL,
Page 44 of 47
LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))SQL Server / Oracle / MS Access:CREATE TABLE Persons(P_Id int NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:MySQL / SQL Server / Oracle / MS Access:CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName))Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the value of the pk_PersonID is made up of two columns (P_Id and LastName).________________________________________SQL PRIMARY KEY Constraint on ALTER TABLETo create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL:MySQL / SQL Server / Oracle / MS Access:ALTER TABLE PersonsADD PRIMARY KEY (P_Id)To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:MySQL / SQL Server / Oracle / MS Access:ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).________________________________________To DROP a PRIMARY KEY ConstraintTo drop a PRIMARY KEY constraint, use the following SQL:MySQL:ALTER TABLE PersonsDROP PRIMARY KEYSQL Server / Oracle / MS Access:ALTER TABLE PersonsDROP CONSTRAINT pk_PersonIDSQL FOREIGN KEY ConstraintA FOREIGN KEY in one table points to a PRIMARY KEY in another table.Let's illustrate the foreign key with an example. Look at the following two tables:------------------------------------------------SQL FOREIGN KEY Constraint on CREATE TABLEThe following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:MySQL:CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,PRIMARY KEY (O_Id),FOREIGN KEY (P_Id) REFERENCES Persons(P_Id))SQL Server / Oracle / MS Access:CREATE TABLE Orders(O_Id int NOT NULL PRIMARY KEY,OrderNo int NOT NULL,P_Id int FOREIGN KEY REFERENCES Persons(P_Id))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(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,
Page 45 of 47
PRIMARY KEY (O_Id),CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)REFERENCES Persons(P_Id))
________________________________________SQL FOREIGN KEY Constraint on ALTER TABLETo create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL:MySQL / SQL Server / Oracle / MS Access:ALTER TABLE OrdersADD FOREIGN KEY (P_Id)REFERENCES Persons(P_Id)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:ALTER TABLE OrdersADD CONSTRAINT fk_PerOrdersFOREIGN KEY (P_Id)REFERENCES Persons(P_Id)
________________________________________To DROP a FOREIGN KEY ConstraintTo drop a FOREIGN KEY constraint, use the following SQL:MySQL:ALTER TABLE OrdersDROP FOREIGN KEY fk_PerOrdersSQL Server / Oracle / MS Access:ALTER TABLE OrdersDROP CONSTRAINT fk_PerOrders
SQL CHECK ConstraintThe CHECK constraint is used to limit the value range that can be placed in a column.If you define a CHECK constraint on a single column it allows only certain values for this column.If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.________________________________________SQL CHECK Constraint on CREATE TABLEThe following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0.MySQL:CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CHECK (P_Id>0))SQL Server / Oracle / MS Access:CREATE TABLE Persons(P_Id int NOT NULL CHECK (P_Id>0),LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:MySQL / SQL Server / Oracle / MS Access:CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes'))
________________________________________SQL CHECK Constraint on ALTER TABLETo create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL:MySQL / SQL Server / Oracle / MS Access:ALTER TABLE PersonsADD CHECK (P_Id>0)To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:MySQL / SQL Server / Oracle / MS Access:
Page 46 of 47
ALTER TABLE PersonsADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
________________________________________To DROP a CHECK ConstraintTo drop a CHECK constraint, use the following SQL:SQL Server / Oracle / MS Access:ALTER TABLE PersonsDROP CONSTRAINT chk_PersonMySQL:ALTER TABLE PersonsDROP CHECK chk_Person
SQL DEFAULT ConstraintThe DEFAULT constraint is used to insert a default value into a column.The default value will be added to all new records, if no other value is specified.________________________________________SQL DEFAULT Constraint on CREATE TABLEThe following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created:My SQL / SQL Server / Oracle / MS Access:CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255) DEFAULT 'Sandnes')The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,OrderDate date DEFAULT GETDATE())
________________________________________SQL DEFAULT Constraint on ALTER TABLETo create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:MySQL:ALTER TABLE PersonsALTER City SET DEFAULT 'SANDNES'SQL Server / Oracle / MS Access:ALTER TABLE PersonsALTER COLUMN City SET DEFAULT 'SANDNES'
________________________________________To DROP a DEFAULT ConstraintTo drop a DEFAULT constraint, use the following SQL:MySQL:ALTER TABLE PersonsALTER City DROP DEFAULTSQL Server / Oracle / MS Access:ALTER TABLE PersonsALTER COLUMN City DROP DEFAULT
Page 47 of 47