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

02. Create Database, Tables and Data Constraints in SQL

Uploaded by

yevob11108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

02. Create Database, Tables and Data Constraints in SQL

Uploaded by

yevob11108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Create Database in SQL

SQL CREATE Database

CREATE DATABASE database_name;


Eg:
CREATE DATABASE GeeksForGeeks;

List Databases in SQL

SHOW DATABASES;

USE Database in SQL | SELECT Database


To use/SELECT a specific database in SQL, we use the USE Statement.

USE database_name

SQL DROP Database

DROP DATABASE database_name;


Eg:
DROP DATABASE GeeksForGeeks;

Q: Is DROP and DELETE command the same?

No DROP and DELETE command are not same. DROP command erases everything whereas
DELETE command erases specific rows.

SQL RENAME Database

ALTER DATABASE database_name MODIFY NAME = new_name;


Tables in SQL
SQL CREATE TABLE

CREATE table table_name


(
Column1 datatype (size),
column2 datatype (size),
.
.
columnN datatype(size)
);

Eg:

CREATE TABLE Employee (


EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);

Inserting Values

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

Eg:

INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)


VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');
Create Table From Another Table

Syntax:

CREATE TABLE new_table_name AS


SELECT column1, column2,…
FROM existing_table_name
WHERE ....... ;

Query:

CREATE TABLE SubTable AS


SELECT CustomerID, CustomerName
FROM customer;

Important: If you try to create a table that already exists, MySQL will throw an error. To avoid this, you
can use the CREATE TABLE IF NOT EXISTS syntax.

SQL Drop Table Statement(DDL)

DROP TABLE table_name;


Eg:
drop table categories;

SQL DELETE Statement

Syntax:
DELETE FROM table_name
WHERE some_condition;

Delete All of the Records

DELETE FROM table_name;


Or
DELETE * FROM table_name;

DELETE is a DML (Data Manipulation Language) command hence operation performed by


DELETE can be rolled back or undone.
SQL RENAME TABLE

ALTER TABLE table_name


RENAME TO new_table_name;

SQL RENAME COLUMN IN A TABLE

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;

To Add a New Column with ALTER TABLE

Syntax
ALTER TABLE table_name
ADD column_name datatype;

Query
ALTER TABLE Student ADD marks INT;

DROP and TRUNCATE in SQL


SQL DROP Statement
Completely removes a table or database from the database, including the data and structure.
Is a permanent operation and cannot be rolled back.
Removes integrity constraints and indexes associated with the table.
Is slower compared to the TRUNCATE statement.

SQL TRUNCATE Statement


Removes all the rows or data from a table, but preserves the table structure and columns.
Is a faster operation compared to the DROP statement.
Resets the identity column (if any) back to its seed value.
Does not remove integrity constraints associated with the table.
Can be rolled back, unlike the DROP statement.

Q: What is Temporary Table in SQL?


Temporary Tables are Created in TempDB and are automatically deleted as soon as the last
connection is terminated.
Temporary Tables helps us to store and process intermediate results.
Temporary tables are very useful when we need to store temporary data.

Syntax:
To Create Temporary Table:
CREATE TABLE #EmpDetails (id INT, name VARCHAR(25))

To Insert Values Into Temporary Table:


INSERT INTO #EmpDetails VALUES (01, 'Lalit'), (02, 'Atharva')

To Select Values from Temporary Table:


SELECT * FROM #EmpDetails

There are 2 types of Temporary Tables:

1. Local Temporary Table:


A Local Temp Table is available only for the session that has created it. It is automatically dropped
(deleted) when the connection that has created it, is closed. To create Local Temporary Table
Single “#” is used as the prefix of a table name. If the Temporary Table is created inside the stored
procedure, it get dropped automatically upon the completion of stored procedure execution.
2. Global Temporary Table:
To create a Global Temporary Table, add the “##” symbol before the table name.
Example:
CREATE TABLE ##EmpDetails (id INT, name VARCHAR(25))

Global Temporary Tables are visible to all connections and Dropped when the last connection
referencing the table is closed. Global Table Name must have an Unique Table Name.

SQL ALTER TABLE – ADD, DROP, MODIFY


ADD Column

ALTER TABLE table_name ADD (Columnname_1 datatype,


Columnname_2 datatype, ..... Columnname_n datatype);

DROP Column

ALTER TABLE table_name


DROP COLUMN column_name;

MODIFY Column

ALTER TABLE table_name


MODIFY column_name column_type;

SQL Data Constraints


In SQL, constraints are some set of rules that are applied to the data type of the specified table, Or we
can say that using constraints we can apply limits on the type of data that can be stored in the
particular column of the table.
The available constraints in SQL are:

NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column
is specified as NOT NULL then we will not be able to store null in this particular column any more.
UNIQUE: This constraint when specified with a column, tells that all the values in the column must
be unique. That is, the values in any row of a column must not be repeated.
PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this
constraint is used to specify a field in a table as primary key.
FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table.
And this constraint is used to specify a field as Foreign key.
CHECK: This constraint helps to validate the values of a column to meet a particular condition.
That is, it helps to ensure that the value stored in a column meets a specific condition.
DEFAULT: This constraint specifies a default value for the column when no value is specified by
the user.

SQL NOT NULL Constraint


SQL NOT NULL on CREATE a Table

CREATE TABLE table_Name(


column1 data_type(size) NOT NULL,
column2 data_type(size) NOT NULL,
......
);

SQL NOT NULL on ALTER Table

ALTER TABLE Emp modify Name Varchar(50) NOT NULL;

UNIQUE Constraint

CREATE TABLE table_Name(


column1 data_type(size) UNIQUE,
column2 data_type(size),
......
);

Unique Constraint on ALTER Table

ALTER TABLE Instructor


ADD UNIQUE(ID);

Primary key constraint in SQL


A primary key constraint depicts a key comprising one or more columns that will help uniquely identify
every tuple/record in a table.

Properties :
No duplicate values are allowed, i.e. Column assigned as primary key should have UNIQUE
values only.
NO NULL values are present in column with Primary key. Hence there is Mandatory value in
column having Primary key.
Only one primary key per table exist although Primary key may have multiple columns.
No new row can be inserted with the already existing primary key.
Classified as : a) Simple primary key that has a Single column 2) Composite primary key has
Multiple column.
Defined in Create table / Alter table statement.

PRIMARY KEY at Column Level :

Syntax :

Create Table Person


(
Id int NOT NULL PRIMARY KEY,
Name varchar2(20),
Address varchar2(50)
);

PRIMARY KEY at Table Level :

Syntax:

Create Table Person


(Id int NOT NULL,
Name varchar2(20),
Address varchar2(50),
PRIMARY KEY(Id, Name)
);

PRIMARY KEY with ALTER TABLE :

Syntax :
Alter Table Person add Primary Key(Id);

- To add Primary key in multiple columns using the following query.


Alter Table Person add Primary Key(Id, Name);
DELETE PRIMARY KEY CONSTRAINT :

To remove Primary Key constraint on table use given SQL as follows.

ALTER table Person DROP PRIMARY KEY;

Foreign Key Constraint in SQL


Foreign Key is a column/field that refers to the primary key/unique key of another table. So it
demonstrates the relationship between tables and acts as a cross reference among them.

A foreign key is created in the CREATE TABLE or ALTER TABLE statement. The foreign key in a table
should match the primary key in the referenced table for every row. This is called Referential Integrity.
Foreign key ensures referential integrity.

The table in which a foreign key is defined is called a Foreign table/Child table/Referencing table. and
the table that defines a primary key and is referenced by a foreign key is called a Primary table/Parent
table /Referenced Table

Properties:

The parent field that is being referenced has to be unique/Primary Key.


The child field may have duplicates and nulls.
Parent records can be deleted if no child exists.
The master table cannot be updated if a child exists.
Must reference PRIMARY KEY in the primary table.
The foreign key column and constraint column should have matching data types.
Records cannot be inserted in the child table if a corresponding record in the master table does
not exist.
Records of the master table cannot be deleted if corresponding records in the child table exist.

Foreign key At column level

CREATE TABLE people (no int references person, Fname varchar2(20));


OR
CREATE TABLE people (no int references person(id), Fname varchar2(20));
Foreign key At table level

CREATE TABLE people(no varchar2(10), fname varchar2(20), foreign key(no) references person);
OR
CREATE TABLE people(no varchar2(10), fname varchar2(20),foreign key(no) references person(id));

Delete Operation in Foreign Key Table


When a record in the master table is deleted and the corresponding record in the child table exists, an
error message is displayed and prevents the DELETE operation from going through.

Error at line 1 : integrity constraint violated - child record found.

Foreign Key with ON DELETE CASCADE


The default behavior of the foreign key can be changed using ON DELETE CASCADE. When this
option is specified in the foreign key definition, if a record is deleted in the master table, all
corresponding records in the detail table will be deleted.

Syntax:

CREATE TABLE people (


no varchar2(10),
fname varchar2(20),
foreign key(no) references 'person' on delete cascade
);

Now deleting records from the person table will delete all corresponding records from the child table.

Foreign Key with ON DELETE SET NULL


A Foreign key with SET NULL ON DELETE means if the record in the parent table is deleted,
corresponding records in the child table will have foreign key fields set to null. Records in the child
table will not be deleted.

Syntax:

CREATE TABLE
people(no varchar2(10), fname varchar2(20), foreign key(no)
references person on delete set null);
Difference Between ON DELETE CASCADE and ON DELETE SET NULL in
DBMS
Composite Key in SQL

Creating table with a composite key:

CREATE TABLE student


(rollNumber INT,
name VARCHAR(30),
class VARCHAR(30),
section VARCHAR(1),
mobile VARCHAR(10),
PRIMARY KEY (rollNumber, mobile));

Q: Can a Composite Key be a Foreign Key in Another Table?

Yes, a composite key can be used as a foreign key in another table within a relational database.

Create the Parent Table


Define the parent table with a composite key.

CREATE TABLE ParentTable (


Column1 datatype1,
Column2 datatype2,
PRIMARY KEY (Column1, Column2)
);

Define the Child Table

CREATE TABLE ChildTable (


ForeignKeyCol1 datatype1,
ForeignKeyCol2 datatype2,
OtherColumns datatype3,
FOREIGN KEY (ForeignKeyCol1, ForeignKeyCol2)
REFERENCES ParentTable(Column1, Column2)
);
CHECK Constraints

CREATE TABLE Student(


ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);

DEFAULT Constraints

CREATE TABLE Student(


ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);

You might also like