0% found this document useful (0 votes)
23 views

Mysql Part 1

SQL is used to store, manipulate, and retrieve data from a database. It was first created in the 1970s by IBM researchers and has since become the standard language for communicating with relational databases. SQL allows users to perform operations like selecting data, inserting rows, updating records, and deleting data from database tables. It includes keywords like SELECT, WHERE, ORDER BY, and operators like =, <, > to query and manipulate data.

Uploaded by

api-681409655
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Mysql Part 1

SQL is used to store, manipulate, and retrieve data from a database. It was first created in the 1970s by IBM researchers and has since become the standard language for communicating with relational databases. SQL allows users to perform operations like selecting data, inserting rows, updating records, and deleting data from database tables. It includes keywords like SELECT, WHERE, ORDER BY, and operators like =, <, > to query and manipulate data.

Uploaded by

api-681409655
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

1.

Introduction to SQL

SQL stands for Structural Query Language, and SQL is used for storing, manipulation, and
retrieving data from the database.
History of SQL

The SQL(Structural Query language) was first created in the 1970s by IBM researchers Raymond
Boyce and Donald Chamberlin. The Query language, known then as SEQUEL, was created
following the publishing of Edgar Frank Todd's paper, In 1970, A Relational Model of Data for
Large Shared Data Banks.
In his paper, Todd proposed that all the data in a database be represented in the form of relations. It
was based on this theory that Chamberlin and Boyce came up with SQL. The original SQL version
was designed to retrieve and manipulate data stored in IBM's original RDBMS known as "System
R." It wasn't until several years later, however, that the Structural Query language was made
available publicly. In 1979, a company named as Relational Software, which later became Oracle,
commercially released its version of the SQL language called Oracle V2.
Since that time, the American National Standards Institute (ANSI) and the International Standards
Organization have deemed the SQL language as the standard language in relational database
communication. While major SQL vendors do modify the language to their desires, most base their
SQL programs off of the ANSI approved version.

What is Database?
A database is a well-ordered collection of data. A database is an electronic system that permits data
to be easily manipulated, accessed, and updated, or an organization uses a database as a method of
managing, storing, and retrieving information. Modern databases are handled using a database
management system (DBMS).

Relational Database
Relational Databases are used to store data in tables (rows and columns). Some common
relational database management systems that use SQL are Oracle, Sybase,
Microsoft SQL Server, Access, Ingres, etc.

                                                                                   
SQL and Relational Databases
A Relational Database contains tables that store the data that is related in some way. SQL is the
query language that allows retrieval and manipulation of table data in the relational database. The
database below has two tables: one with data on Users and another with data on Products.    

      

1. SQL QUERY 

A database most often contains tables. Some name identifies each table. The table includes
records(rows) with Data. To access those records, we need SQL Syntax. Most of the action you
need to perform Database by using the SQL Statement.
Note: SQL keywords are not case-sensitive (e.g., select as SELECT)
 The syntax of the language describes the language element.
 SQL syntax is somewhat like simple English sentences.
 Keywords include SELECT, UPDATE, WHERE, ORDER BY ETC.
Four fundamental operations that can apply to any databases are:
1. Read the Data -- SELECT
2. Insert the new Data -- INSERT
3. Update existing Data -- UPDATE
4. Remove Data –DELETE
These operations are referred to as the CRUD (Create, Read, Update, Delete).

The SQL SELECT QUERY

The SELECT statement permits you to read data from one or more tables.
The general syntax is:
SELECT first_name, last_name
   FROM customer;
Example: Read the  first_name and last_name from table customer.

To select all columns, use *


SELECT *
   FROM customer;

The SQL SELECT DISTINCT


The SELECT DISTINCT statement is to return the different values.
SELECT DISTINCT first_name
FROM  customer;
The SQL WHERE CLAUSE
The WHERE clause allows the user to filter the data from the table. The WHERE clause allows the
user to extract only those records that satisfy a specified condition.
When we access, the Text value
SQL requires single quotes around text values (many database systems will also use double
quotes). And numeric fields should not be enclosed in quotes.
SELECT first_name FROM customer
WHERE last_name = ‘perry’;

When we access the Numeric field


SELECT first_name , last_name  FROM customer WHERE active = 0;
Operators in where clause
= Equal 
> Greater than
< Less than
>= Greater than equal 
<= Less than equal 
<> Not equal (also written as !=)
BETWEEN Between a range 
LIKE Search for  pattern 
IN Specify multiple possible values for a column

The SQL WHERE CLAUSE WITH AND, OR & NOT 


A WHERE clause with AND:
SELECT first_name, email, address_id
  FROM customer
 WHERE fisrt_name = ‘IAN’ AND last_name = ‘STILL’
A WHERE clause with OR:
UPDATE customer
SET first_name = ‘jingle’
WHERE last_name = ‘ GREY’;

A WHERE clause with NOT:


Select  store_id, first_name,last_name, email, address_id FROM customer 
WHERE NOT store_id = 2;

The SQL ORDER BY


Order by is used to print the values from the table in order(ascending or descending)
Order By in Descending order
SELECT first_name, last_name,email
FROM customer
ORDER BY first_name DESC;
Order By in Ascending order
SELECT first_name, last_name,email
FROM customer
ORDER BY first_name ASC;

The SQL SELECT TOP CLAUSE


The SELECT TOP is used to specify the number of records from the to return. The SELECT TOP
is useful on large tables with millions of records. It is returning a large number of records that can
impact performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT
clause to select a limited number of records, while Oracle uses ROWNUM.

MySQL Syntax:
SELECT first_name, last_name,email
FROM customer WHERE first_name = ‘AUSTIN’
LIMIT 20;
The SQL MIN() AND MAX() FUNCTION
The MIN() function in SQL returns the smallest value of the selected column from the table. The
MAX() function in SQL returns the largest value of the selected column from the table.
MIN() Syntax
SELECT MIN(address_id)
FROM customer;

MAX() Syntax
SELECT MAX(address_id)
FROM customer;
  

The SQL COUNT(), AVG() AND SUM() FUNCTION


The COUNT()  function gives the number of rows that matches specified conditions. And the 
AVG() function in SQL returns the average value of a numeric column. The SUM() function in
SQL returns the total sum of a numeric column.
COUNT() Syntax
SELECT COUNT(email)
FROM customer;

AVG() Syntax
SELECT AVG(active)
FROM customer;

SUM() Syntax
SELECT SUM(active)
FROM customer
The SQL LIKE-OPERATOR
The LIKE operator is used with the WHERE clause to find for a specified pattern in an attribute.
The two wildcards are used in conjunction with the LIKE operator: 
 %  - it represents zero, one, or multiple characters
 _   -  it represents a single character
Note: MS Access uses an asterisk (*) in place of the percent sign (%)and a question mark (?) in
place of the underscore (_).
The ‘%’ and the ‘_’ can also be used in combinations.

LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column LIKE pattern;

Selects all columns of the customer with a first_name starting with "D".
SELECT * FROM customer
WHERE first_name LIKE 'D%';

Selects all columns of the customer with a first_name Ending with "E":
SELECT * FROM customer
WHERE first_name LIKE '%E';

Selects all columns of the customer with a first_name that have "or" in any position.
SELECT * FROM customer
WHERE first_name LIKE '%or%';

Selects all columns of the customer with a first_name that starts with "a" and ends with "o":
SELECT * FROM customer
WHERE first_name LIKE 'a%o';
Selects all columns of the customer with a first_name that starts with "a" and are at least six
characters in length:
SELECT * FROM customer
WHERE first_name LIKE 'a__%';

The SQL IN AND NOT IN OPERATORS


The IN operator allows users to specify multiple values in a WHERE clause.  The IN operator is a
shorthand for various OR conditions.
IN 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);

Selects all the columns of customer whose customer_id in (1,2,3):


SELECT * FROM customer
WHERE cutomer_id IN (1,2,3);

Selects all the columns of customer whose customer_id in (1,2,3):


SELECT * FROM customer
WHERE cutomer_id  NOT IN (1,2,3);

The SQL BETWEEN OPERATOR


The BETWEEN operator retrieves values within the given range. The values can be texts,
numbers, 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;
Select all the columns from the customer with customer_id between 1 to 20.
SELECT * FROM customer WHERE customer_id BETWEEN 1 AND 20;

Select all the columns from the customer with customer_id, not between 1 to 570.
SELECT * FROM customer WHERE customer_id NOT BETWEEN 1 AND 570;
The SQL ALIAS
Aliases are used to give a nickname to a column in a table, a temporary name.  Aliases are used to
make column names more readable to the user. 
Alias Column Syntax
SELECT first_name AS first, last_name AS last
FROM customer;
Creates two aliases, one for the first_name column and one for the last_name column:

Alias Table Syntax


SELECT c.first_name, c.last_name
FROM customer AS c
Create an alias for the customer table
The SQL GROUP BY STATEMENT
The GROUP BY used to group rows from the table. And it has the same values as summary rows.
For example, find the number of customers in each country, The GROUP BY is often used with
aggregate functions like (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more
columns.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Count the number of active and non-active customers 
SELECT COUNT(customer_id) FROM customer GROUP BY active

The SQL HAVING CLAUSE


The HAVING clause is added to SQL because the WHERE keyword can not be used with
aggregate functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
List the number of continents which has a region more than 6.
SELECT * from country group by(continent) having count(region) >6; 

The SQL UNION 


The UNION operator allows the user to combine the result-set of two or more SELECT statements
in SQL. Each SELECT statement within UNION should have the same number of columns. The
columns in each SELECT statement should also be in the same order. The columns should also
have similar data types.
The SQL UNION 
Select  column_name(s) from table1
UNION
Select column_name(s) from table2;

UNION ALL Query


The UNION operator selects only different values by default. To allow duplicate values, the user
can use UNION ALL operator.
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the output are usually equal to the column names in the first SELECT
statement in the UNION.

The SQL STORED PROCEDURE


What is a SQL Stored Procedure?
The stored procedure is a prepared SQL query that you can save so that the query can be reused
over and over again. So, if the user has an SQL query that you write over and over again, keep it as
a stored procedure and execute it. Users can also pass parameters to a stored procedure so that the
stored procedure can act based on the parameter value that is given.

Stored Procedure Syntax


CREATE PROCEDURE procedure_name
AS
sql_statement
GO; 
Execute a Stored Procedure
EXEC procedure_name;

2. SQL JOIN

The SQL Join help in retrieving data from two or more database tables. The tables are mutually
related using primary keys and foreign keys. 

Type of Join

INNER JOIN
The INNER JOIN is used to print rows from both tables that satisfy the given condition. For
example, the user wants to get a list of users who have rented movies together with titles of movies
rented by them. Users can use an INNER JOIN for that, which returns rows from both tables that
satisfy with given conditions.  

                                 
Fig. INNER JOIN
The INNER JOIN keyword selects records that have matching values in both the tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

SELECT city.city_id, country.country, city.last_update, country.last_update FROM city


INNER JOIN country ON city.country_id = country.country_id

LEFT JOIN
The LEFT JOIN returns all the records from the table1 (left table) and the matched records from
the table2 (right table). The output is NULL from the right side if there is no match.

                                            
Left Join

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SELECT city.city_id, country.country, city.last_update, country.last_update FROM city
LEFT JOIN country ON city.country_id = country.country_id

RIGHT JOIN
The RIGHT JOIN is the opposite of LEFT JOIN. The RIGHT JOIN prints all the columns from the
table2(right table) even if there no matching rows have been found in the table1 (left table). If there
no matches have been found in the table (left table), NULL is returned.
                                                
RIGHT JOIN
RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2  ON table1.column_name = table2.column_name;
SELECT city.city_id, country.country, city.last_update, country.last_update FROM city
RIGHT JOIN country ON city.country_id = country.country_id

Full OUTER JOIN


The FULL OUTER JOIN keyword returns all records when there are a match in left (table1) or
right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-sets!

                                         
Full Join
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name WHERE condition;
Note: MySQL does not support the Full Join, so we can perform left join and right join separately
then take the union of them.
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
   
SELF-JOIN
A self-JOIN is a regular join, but the table is joined with itself.
Self -JOIN Syntax
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

3. SQL DATABASE
The SQL CREATE DATABASE STATEMENT
The CREATE DATABASE statement in SQL is used to create a new SQL database.
Syntax
CREATE DATABASE database_name;
Let’s create a database and give name as testdb
CREATE database testdb;

              
Now, let’s check the databases in MySQL by using show databases query.
Show databases;

                          

The SQL DROP DATABASE STATEMENT


The DROP DATABASE statement in SQL is used to drop an existing SQL database.
Syntax
DROP DATABASE database_name;

Let’s drop the created database by using drop database testdb.


DROP database testdb;

           
Now, let’s check the databases in MySQL by using show databases query after dropping the
testdb.
SHOW databases;

                           
The created database(testdb) has been dropped.

The SQL CREATE TABLE


The CREATE TABLE statement in SQL is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
    column1 data_type,
    column2 data_type,
    column3 data_type,
   ....
);
The column1, column2, ….., specify the names of the columns of the table. The datatype parameter
specifies the type of data the column can hold (e.g., varchar, integer, date, etc.)

Let’s create a customer table


CREATE TABLE cutomer(id integer, first_name varchar(10), last_name varchar(10), city
varchar(10), country varchar(15), phone varchar(15));

To check the schema of the table, use desc table_name.


DESC customer;
        

The SQL DROP TABLE STATEMENT


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

   
The table has dropped after running the query drop table table_name. As we can see, the table does
not exist after dropped.
Now we are going to create the same table again to insert the values in that table.

The SQL INSERT INTO STATEMENT


The INSERT INTO statement in SQL is used to insert new records in a table.
INSERT INTO query
We can write the INSERT INTO statement in two ways. The first way is to specify both the column
names and the values to be inserted:
INSERT INTO customer(id , first_name, last_name ,city ,country,phone)VALUES (2,
‘Ana’, ‘Trujillo’, ‘Mexico’, ‘Mexico’,  (5) 555-4729);
If users are adding values for all the columns of the table, you don’t need to specify the particular
column names in the SQL query. However, ensure the order of the values is in the same order as
the columns in the table. 
The INSERT INTO query would be as follows:
INSERT INTO customer
VALUES (3, ‘Antonio, ‘Moreno, ‘Mexico’, ‘Mexico’,  (5) 555-3932);

      
We have inserted two rows yet. Similarly, we can insert many rows in the table. Finally, we have
added ten rows as we can see in the picture below.

SELECT * FROM customer;

The SQL NULL VALUES


What is a NULL Value?
The field with a NULL value is a field with no value. If the field in a table is optional, to insert new
data or update data without adding a value to this field and Then, the field will be saved as a NULL
value.
Note: A NULL value is not the same as a zero value, or we can say a field that holds spaces. The
field with a NULL value is one that has been left blank during record creation!
Insert the NULL values in tables
INSERT INTO customer VALUES(11, ‘Victoria’, ‘Ashworth’, ‘London’, NULL, ‘(171) 555-
1212’)

As we can able to see, the last row contains one NULL value.
How to check for NULL Values?
To test for NULL values in the table has to use the IS NULL and IS NOT NULL operators
instead.
IS NULL Syntax
SELECT *
FROM customer  WHERE country IS NULL;

IS NOT NULL Syntax


SELECT *  FROM customer
WHERE country IS NOT NULL;
It will return those countries which have some values(expect Null values).

The SQL UPDATE STATEMENT


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

UPDATE Syntax
UPDATE customer
SET country = ‘Mexico’  WHERE id = 11;

We have updated the null value of the country with Mexico.

The SQL DELETE STATEMENT


The DELETE statement in SQL is used to delete existing records in a table.
DELETE Syntax
DELETE FROM customer WHERE id = 11;

We have deleted one row, which contains id = 11.

The SQL ALTER TABLE STATEMENT


The ALTER TABLE statement in SQL is used to add, modify, or delete columns in an existing
table. And it also used to add and drop various constraints on a current table.
1. ALTER TABLE - ADD COLUMN IN EXISTING TABLE

To add a  new column in a table, use the SQL query


ALTER TABLE customer
ADD email varchar(25);
2. ALTER TABLE – MODIFY/ALTER COLUMN

To change the data type of column values in a table, use the following syntax:
ALTER TABLE customer  ADD COLUMN dob date;

      
We have assigned the dob with the datatype date. But now we want to change the datatype from
date to year.
ALTER TABLE customer MODIFY dob year;

       

3. ALTER TABLE - DROP COLUMN

To delete a specific column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):
Syntax: 
ALTER TABLE customer
DROP COLUMN email;  

4. The SQL CONSTRAINTS

The Constraints in SQL can be specified when the table is created with the CREATE TABLE
statement, or after the table is altered 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 any rules for the records in a table. Constraints can be used to
limit the type of data that can go into a table. It ensures the accuracy and reliability of the records in
the table, and if there is any violation between the constraint and the record 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 constraints are commonly used in SQL
CONSTRAINT DESCRIPTION
S
Not Null It Ensures that a column cannot have a NULL value.
Unique It Ensures that all the values in a column are unique.
Primary Key It is a combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table.
Foreign Key Uniquely identifies a record /row in another table
Check It checks that all values in a column satisfy a specific condition
Default It gives a default value for a column when no value is specified
Index It is Used to create and retrieve data from the database quickly.
 
NOT NULL CONSTRAINTS
The NOT NULL constraint enforces a column NOT to accept NULL values.  This imposes a field
always to contain a value, which means that the user cannot insert a new record in a table or update
a record without adding a value to this field.
NOTE: By default, a column can hold NULL values.

Create a table using SQL not null constraints


The following SQL ensures that the "id", "First_name" and "Last_name" columns will NOT accept
NULL values when the "student" table is created:
Example
CREATE TABLE student(
     id int NOT NULL,
first_name varchar(25) NOT NULL, 
     last_name varchar(25) NOT NULL,   
     age int
);

In the above table, it has specified the id, first_name, and last_name as not null and age as null.

SQL NOT NULL on ALTER table Statement


To make a NOT NULL constraint on the "age" column when the "student" table is already created,
use the following SQL:
Example:
ALTER TABLE student
MODIFY age int NOT NULL;
                   
In the above table, it has specified the id, first_name,last_name, and age as not null.

SQL UNIQUE CONSTRAINT


The UNIQUE constraint in SQL ensures that all values in a column are distinct. UNIQUE and
PRIMARY KEY constraints both provides a guarantee for uniqueness for a column or group of
columns. A PRIMARY KEY constraint, by default, has a UNIQUE constraint. However, the user
can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

Creates UNIQUE constraint on the "id" column when the "person" table is created
CREATE TABLE person (
     id int NOT NULL,
    last_name varchar(255) NOT NULL,
    first_name varchar(255),
    age int,
     UNIQUE (ID)
);
        
We have applied unique constraints on id, and as we can see, it is showing as the primary key.

Create a UNIQUE constraint on the "first_name" column when the "persons" table already
exists.
ALTER TABLE persons
ADD UNIQUE (first_name);

            
Now we have two unique constraints(id and first_name) in the person table.

To name the UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following SQL syntax:
ALTER TABLE person
ADD CONSTRAINT UC_person UNIQUE (age, last_name);

                
Here the age and last_name are converted as unique constraints.

DROP A UNIQUE CONSTRAINT


To drop a UNIQUE constraint, use the SQL query
ALTER TABLE person
DROP INDEX UC_Person;

 
As we can see in the person table The unique constraint(UC_Persons) has been dropped.

SQL PRIMARY KEY CONSTRAINTS


The PRIMARY KEY constraint uniquely identifies each of the records in a table. Only ONE
primary key can have in a table. And also, in the table, this primary key can consist of single or
multiple columns (fields). Primary keys should contain UNIQUE values, and cannot contain NULL
values.
CREATE TABLE person(ID int NOT NULL, last_name varchar(255) NOT NULL,
first_name varchar(255), age int, PRIMARY KEY(ID));

             

To allow the naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the SQL syntax.
CREATE TABLE person (
     id int NOT NULL,
    last_name varchar(255) NOT NULL,
    first_name varchar(255),
     age int,
    CONSTRAINT PK_person PRIMARY KEY (id,last_name)
);

           
Note: In this example, there is only ONE PRIMARY KEY as PK_Person. And the VALUE of the
primary key is made up of two columns (id+ last_name).

SQL PRIMARY KEY on ALTER TABLE


Create a PRIMARY KEY constraint on the column_name "id" when the table_name(student) is
already created, use the following SQL:
ALTER TABLE student
ADD PRIMARY KEY (id);

Here we have assigned the primary key as “id” on the student table.
Allow the naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint
on multiple columns, use the SQL query:
ALTER TABLE student
ADD CONSTRAINT PK_student PRIMARY KEY (id,first_name);

                 

DROP PRIMARY KEY CONSTRAINTS


To drop the  PRIMARY KEY constraint from the table, use the SQL Query:
ALTER TABLE student
DROP PRIMARY KEY;

As we can see from the student table, the primary key has been dropped from the table.

SQL FOREIGN KEY CONSTRAINT


A FOREIGN KEY is used to link two tables together. It is sometimes also called a referencing key.
Foreign Key is a combination of columns (can be single column) whose value matches a Primary
Key in the different tables. The relationship between two tables matches the Primary Key in one of
the tables with a Foreign Key in the second table. If the table contains a primary key defined on any
field, then the user should not have two records having the equal value of that field.
Let’s create two tables using the foreign key.
CUSTOMER table
CREATE TABLE customer(
   Id int NOT NULL,
   Name varchar(20)   NOT NULL,
    Age int NOT NULL,
    Address varchar(25) ,
   Salary decimal (18, 2),       
    PRIMARY KEY (id)
);
         

         
 
Order Table  with Foreign key
CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT NULL, Id int,
PRIMARY KEY(OrderID), CONSTRAINT FK_customerOrder FOREIGN KEY(Id));
             
Here the Id is the primary key for the customer table and foreign key for orders table.

FOREIGN KEY on ALTER TABLE


To create the FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the SQL query: 
ALTER TABLE Orders
ADD FOREIGN KEY (ID) REFERENCES customer(id);

DROP A FOREIGN KEY CONSTRAINT


To drop a FOREIGN KEY constraint from the table, use the SQL query:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
                   

SQL CHECK CONSTRAINTS


The CHECK CONSTRAINTS is used to limit the range of value that can be placed in a column if
the user defines a CHECK constraint on a single column, it allows only specific values for the
column. If the user defines a CHECK constraint on a table, it can limit the values in particular
columns based on values in another column in the row.

SQL CHECK on CREATE TABLE


SQL Query to creates a CHECK constraint on the column "Age" when the table "Persons" is
created. The CHECK constraint makes sure that the user can not have any person below 18 years:
CREATE TABLE Persons (
     ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
     Age int,
    CHECK (Age>=18)
);

        
Here we have created the Persons table and given a check constraint on the Age column. If the
Age<18, then it will throw an error, as shown below.
INSERT INTO Persons VALUES(1, ‘abc’, ‘aaa’, 17);

     

For creating a CHECK constraint on multiple columns in the table, use the SQL syntax:
            

CHECK on ALTER TABLE


Create a CHECK constraint on the column "Age" when the table is already created, use the
following SQL:
ALTER TABLE Persons
ADD CHECK (Age >= 18)

       
Defining CHECK constraint on multiple columns of a table, use the SQL query:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
  

DROP A CHECK CONSTRAINT


To drop a CHECK constraint from the table, use the following SQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;

                       
Here we have dropped the CHK_PersonAge constraints by using the drop statement.

SQL DEFAULT CONSTRAINT


The DEFAULT constraint in SQL is used to provide a default value for a column of the table. The
default value will be added to every new record if no other value is mentioned.

SQL DEFAULT on CREATE TABLE


The SQL query to sets a DEFAULT value for the "City" column when the "Persons" table is
created
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
     City varchar(255) DEFAULT 'Sandnes'
);

As we can see in the Persons table, the city name is written as Sandnes by Default.

SQL DEFAULT on ALTER TABLE


To create a DEFAULT constraint on the column "City" when the table is already created, use the
following SQL:
ALTER TABLE Persons
ALTER Age SET DEFAULT 20;

      

DROP A DEFAULT CONSTRAINT


To drop a DEFAULT constraint from the table, use the SQL query:
ALTER TABLE Persons
ALTER City DROP DEFAULT;

             
As we can see in the Persons table, the default value of the city has been removed.

You might also like