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

Tables in sql

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

Tables in sql

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

Tables in sql:

SQL CREATE TABLE

The SQL CREATE TABLE statement is a foundational command used to define and structure a new
table in a database. By specifying the columns, data types, and constraints such as PRIMARY
KEY, NOT NULL, and CHECK, helps you design the database schema.

In this article, we’ll learn the syntax, best practices, and practical examples of using the CREATE
TABLE statement in SQL. We’ll also cover how to create tables from existing data and troubleshoot
common errors.

SQL CREATE TABLE Statement

To create a new table in the database, use the SQL CREATE TABLE statement. A table’s structure,
including column names, data types, and constraints like NOT NULL, PRIMARY KEY, and CHECK, are
defined when it is created in SQL.

The CREATE TABLE command is a crucial tool for database administration because of these
limitations, which aid in ensuring data integrity.

Syntax:

To create a table in SQL, use this CREATE TABLE syntax:

CREATE table table_name


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

 table_name: The name you assign to the new table.

 column1, column2, … : The names of the columns in the table.

 datatype(size): Defines the data type and size of each column.

Here table_name is name of the table, column is the name of column

SQL CREATE TABLE Example

Let’s look at examples of CREATE TABLE command in SQL and see how to create table in SQL.

CREATE TABLE in SQL and Insert Data

In this example, we will create a new table and insert data into it.

Let us create a table to store data of Customers, so the table name is Customer, Columns are Name,
Country, age, phone, and so on.

CREATE TABLE Customer(

CustomerID INT PRIMARY KEY,


CustomerName VARCHAR(50),

LastName VARCHAR(50),

Country VARCHAR(50),

Age INT CHECK (Age >= 0 AND Age <= 99),

Phone int(10)

);

Output:

To add data to the table, we use INSERT INTO command, the syntax is as shown below:

Syntax:

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

Example Query

This query will add data in the table named Subject

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

Output:
Create Table From Another Table

We can also use CREATE TABLE to create a copy of an existing table. In the new table, it gets the exact
column definition all columns or specific columns can be selected.

If an existing table was used to create a new table, by default the new table would be populated with
the existing values from the old 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;

Output:

Note: We can use * instead of column name to copy whole table to another table.

Important Points About SQL CREATE TABLE Statement

 CREATE TABLE statement is used to create new table in a database.

 It defines the structure of table including name and datatype of columns.

 The DESC table_name; command can be used to display the structure of the created table

 We can also add constraint to table like NOT NULL, UNIQUE, CHECK, and DEFAULT.

 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

Last Updated : 27 Nov, 2024

The DROP TABLE command in SQL is a powerful and essential tool used to permanently delete a
table from a database, along with all of its data, structure, and associated constraints such as
indexes, triggers, and permissions. When executed, this command removes the table and all its
contents, making it unrecoverable unless backed up.

In this article, We will learn about SQL DROP TABLE by understanding its examples, and cover
important points to help you manage your database tables effectively.

DROP TABLE in SQL

 The DROP TABLE statement in SQL is used to delete a table and all of its data from the
database permanently.

 This operation cannot be undone, and once the table is dropped all data in that table is lost.

 Once executed, this operation removes the table definition and all of its rows, so the table
can no longer be accessed or used.

 This action is irreversible which means that once a table is dropped, it cannot be recovered
unless there is a backup.

Syntax:

The syntax to use the DROP TABLE command in SQL is:

DROP TABLE table_name;

The syntax of the command remains the same in Oracle, SQL Server and MySQL.

Example of DROP TABLE in SQL

To demonstrate how to use the DROP TABLE command, let’s first create a database and a table, and
then we will drop it.

Step1: First, we will create a database and table on which the SQL queries will be run.

CREATE DATABASE NewCafe;

USE NewCafe;

CREATE TABLE categories (

CategoryID INT NOT NULL PRIMARY KEY,

CategoryName NVARCHAR(50) NOT NULL,

ItemDescription NVARCHAR(50) NOT NULL


);

INSERT INTO categories (CategoryID, CategoryName, ItemDescription)

VALUES

(1, 'Beverages', 'Soft Drinks'),

(2, 'Condiments', 'Sweet and Savory Sauces'),

(3, 'Confections', 'Sweet Breads');

SELECT * FROM categories;

Output:

At this point, the categories table has been created with three rows of sample data.

Step2: Now, let’s use the DROP TABLE statement to delete the categories table permanently

Query:

DROP TABLE categories;

Output:

Important Points About SQL DROP TABLE

 The SQL DROP TABLE statement is used to delete tables in a database, along with all
associated data, indexes, triggers, constraints and permission specifications.
 The table will be permanently disable, so use this query with caution.

 Use DROP TABLE IF EXISTS query to prevent errors when dropping a table that does not exist

 When dropping a partitioned table, the DROP TABLE statement removes the table definition,
all partitions, all data stored in those partitions, and all partition definitions.

 The DROP TABLE statement can be used to drop temporary tables by including
the TEMPORARY keyword.

 To verify if a table is dropped, you can use the DESC command.

Conclusion

The DROP TABLE command is an essential SQL function that helps in maintaining and cleaning up
database environments. Its ability to permanently remove tables and all related data makes it a
powerful tool, but it should be used cautiously to avoid accidental data loss. Understanding its
syntax, options for error prevention, and its role in managing both regular and temporary tables is
key to effective database management.

SQL DELETE Statement

Last Updated : 28 Nov, 2024

The SQL DELETE statement is one of the most commonly used commands in SQL (Structured Query
Language). It allows you to remove one or more rows from the table depending on the situation.
Unlike the DROP statement, which removes the entire table, the DELETE statement removes data
(rows) from the table retaining only the table structure, constraints, and schema

In this article, we’ll learn the syntax and usage of the SQL DELETE statement with detailed examples,
including how to delete a single record, delete multiple records, and delete all records from a table.

SQL DELETE Statement

The SQL DELETE statement removes one or more rows from a database table based on a condition
specified in the WHERE clause. It’s a DML (Data Manipulation Language) operation that modifies the
data within the table without altering its structure.

Syntax:

DELETE FROM table_name

WHERE some_condition;

Parameter Explanation

 Some_condition: condition to choose a particular record.

 table_name: name of the table


Note: We can delete single as well as multiple records depending on the condition we provide in the
WHERE clause. If we omit the WHERE clause then all of the records will be deleted and the table will
be empty.

The sample table is as follows GFG_Employees:

Examples of SQL DELETE Statement

Assume we have created a table named GFG_Employee in SQL which contains the personal details of
the Employee including their id, name, email and department etc. as shown below −

CREATE TABLE GFG_Employees (

id INT PRIMARY KEY,

name VARCHAR (20) ,

email VARCHAR (25),

department VARCHAR(20)

);

INSERT INTO GFG_Employees (id, name, email, department) VALUES

(1, 'Jessie', '[email protected]', 'Development'),

(2, 'Praveen', '[email protected]', 'HR'),

(3, 'Bisa', '[email protected]', 'Sales'),

(4, 'Rithvik', '[email protected]', 'IT'),

(5, 'Suraj', '[email protected]', 'Quality Assurance'),

(6, 'Om', '[email protected]', 'IT'),

(7, 'Naruto', '[email protected]', 'Development');

Select * From GFG_Employees

Output

GFG_Employees
Example 1: Deleting Single Record

We can use the DELETE statement with a condition to delete a specific row from a table.
The WHERE clause ensures only the intended record is removed. We can delete the records named
Rithvik by using the below query:

Query:

DELETE FROM GFG_Employees WHERE NAME = 'Rithvik';

Output:

Example 2: Deleting Multiple Records

Delete the rows from the table GFG_Employees where the department is “Development”. This will
delete 2 rows(the first row and the seventh row).
Query

DELETE FROM GFG_Employees

WHERE department = 'Development';

Output

output

Example 3: Delete All of the Records

To remove all the entries from the table, you can use the following query:

Query:

DELETE FROM GFG_EMPLOyees;

Or

DELETE * FROM GFG_EMPLOyees;

Output:

All of the records in the table will be deleted, there are no records left to display. The table
GFG_EMPLOyees will become empty.

output

Rolling Back DELETE Operations

Since the DELETE statement is a DML operation, it can be rolled back when executed in a statement.
If you accidentally delete records or need to repeat the process, you can use
the ROLLBACK command.

Query:

START TRANSACTION;

DELETE FROM GFG_Employees WHERE department = 'Development';

-- If needed, you can rollback the deletion

ROLLBACK;

Best Practices for Using SQL DELETE


 Use Transactions: Wrap DELETE statements in transactions to provide an option to roll back
changes if necessary.

 Always Use a WHERE Clause: Avoid deleting all rows by accident. Always filter records using
a WHERE clause to specify which rows to delete.

 Backup Data: Before performing large deletions, ensure that you have a backup of the data
to avoid irreversible loss.

 Test on Development Server: Always test your DELETE queries on a development or staging
environment to ensure they produce the desired result.

 Optimize Deletions: For large datasets, delete records in batches to reduce performance
impact.

Conclusion

The SQL DELETE statement is a powerful tool for removing data from a database table based on
specific conditions. By understanding the correct syntax, how to delete individual or multiple records,
and how to handle performance issues, you can use the DELETE statement efficiently and safely.

Always be careful when deleting data, especially when working with large tables or sensitive
information. By following best practices and using habits, you can ensure that your data remains
authentic and secure.

ALTER (RENAME) in SQL

Last Updated : 21 Nov, 2024

In SQL, making structural changes to a database is often necessary. Whether it’s renaming a table or
a column, adding new columns, or modifying data types, the SQL ALTER TABLE command plays a
critical role. This command provides flexibility to manage and adjust database schemas without
affecting the existing data.

In this article, we will explain how to rename tables and columns in SQL using the ALTER TABLE
command, along with practical examples. We’ll also cover how these commands vary across
databases like MySQL, MariaDB, and Oracle. This comprehensive guide ensures our queries
are accurate, efficient, and SEO-optimized.

What is the ALTER Command in SQL?

The structure of an existing table can be changed by users using the SQL ALTER TABLE command. If
we need to rename a table, add a new column, or change the name of an existing column in SQL,
the ALTER command is crucial for making schema changes without affecting the data that is already
there. This is essential for tasks like:

 Renaming a table.
 Changing a column name.

 Adding or deleting columns.

 Modifying the data type of a column.

Syntax

1. Renaming a Table

ALTER TABLE table_name


RENAME TO new_table_name;

2. Renaming a Column

ALTER TABLE table_name


RENAME COLUMN old_column_name TO new_column_name;

3. Adding a New Column

ALTER TABLE table_name


ADD column_name datatype;

4. Modifying a Column Data Type

ALTER TABLE table_name


MODIFY COLUMN column_name new_datatype;

Examples of ALTER Command in SQL

Below are practical examples to help us understand how to use the ALTER command effectively in
various scenarios. These examples includes renaming tables or columns, adding new columns,
or changing column data types.

1. Create a Sample Table

First, let’s create a sample table to demonstrate the ALTER command:

CREATE TABLE Student (


id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
email VARCHAR(50),
phone VARCHAR(20)
);

2. Insert Data into the Table

Let’s insert some data and then perform ALTER operation to understand better about alter
command.

INSERT INTO Student (id, name, age, email, phone)


VALUES
(1, 'Amit', 20, '[email protected]', '9999999999'),
(2, 'Rahul', 22, '[email protected]', '8888888888'),
(3, 'Priya', 21, '[email protected]', '7777777777'),
(4, 'Sonia', 23, '[email protected]', '6666666666'),
(5, 'Kiran', 19, '[email protected]', '5555555555');

Output

Student Table

Example 1: Rename a Column

Change the name of column name to FIRST_NAME in table Student. To change the column name of
the existing table we have to use Column keyword before writing the existing column name to
change

Syntax

ALTER TABLE Student RENAME COLUMN Column_NAME TO FIRST_NAME;

Query:

ALTER TABLE Student RENAME Column name TO FIRST_NAME;

Output

Output

Example 2: Rename a Table

In this example, the table name Student is changed to Student_Details using the ALTER
TABLE command, making the name more descriptive and relevant to its content.

Query:

ALTER TABLE Student RENAME TO Student_Details;

Output
Student_Details table

Example 3: Add a New Column

To add a new column to the existing table, we first need to select the table with ALTER
TABLE command table_name, and then we will write the name of the new column and its datatype
with ADD column_name datatype. Let’s have a look below to understand better.

Syntax

ALTER TABLE table_name


ADD column_name datatype;

Query:

ALTER TABLE Student ADD marks INT;

Output

output

5. Modify a Column Data Type

In the example, the phone column is updated from VARCHAR(20) to BIGINT to store numerical data
more efficiently and ensure data integrity for phone numbers without unnecessary characters.

Syntax

ALTER TABLE table_name


MODIFY COLUMN column_name new_datatype;

Query:

ALTER TABLE Student_Details


MODIFY COLUMN phone BIGINT;

Output
id name age email phone

1 Amit 20 [email protected] 9999999999

2 Rahul 22 [email protected] 8888888888

3 Priya 21 [email protected] 7777777777

4 Sonia 23 [email protected] 6666666666

5 Kiran 19 [email protected] 5555555555

Explanation:

 The phone column now has a BIGINT data type, suitable for storing large numeric values.

 Existing data remains unchanged but is stored as integers instead of strings.

Conclusion

The SQL ALTER TABLE command is an effective way to modify the structure of an already-existing
tables in a database. When necessary, we can use ALTER TABLE to rename the entire table, rename a
specific column in SQL, or change a column name to something more descriptive. This command is
important for database administration since it also enables the addition of new columns and
the modification of data types.

DROP and TRUNCATE in SQL

Last Updated : 28 Nov, 2024

The DROP and TRUNCATE commands in SQL are used to remove data from a table, but they work
differently. Understanding the difference between these two commands is important for
proper database management, especially when dealing with large amounts of data.

This article provides an in-depth explanation of the DROP and TRUNCATE commands in SQL, their
main differences, usage, and detailed examples. By the end of this article, We will be ready to use
these commands effectively and understand their impact on your database.

What is the SQL DROP Command?


In SQL, the DROP command is used to permanently remove an object from a database, such as a
table, database, index, or view. When you DROP a table, the table structure and its data are
permanently deleted, leaving no trace of the object.

Syntax:

DROP object object_name ;

DROP Command Examples

Let’s look at some examples of the DROP statement in SQL.

DROP Table

Syntax:

DROP TABLE table_name;

table_name: Name of the table to be deleted.

DROP database

Syntax:

DROP DATABASE database_name;

database_name: Name of the database to be deleted.

What is TRUNCATE Command?

The TRUNCATE command is a Data Definition Language (DDL) action that removes all rows from a
table but preserves the structure of the table for future use. Although TRUNCATE is similar to the
DELETE command (without the WHERE clause), it is much faster because it bypasses certain integrity
constraints and locks. It was officially introduced in the SQL:2008 standard.

Syntax:

TRUNCATE TABLE table_name;

Where,

 table_name: Name of the table to be truncated.

 DATABASE name: student_data

Differences Between DROP and TRUNCATE

The key differences between DROP and TRUNCATE statements are explained in the following table:

DROP TRUNCATE

In the drop table data and its definition is deleted It preserves the structure of the table for
with their full structure. further use exist but deletes all the data.
DROP TRUNCATE

Drop is used to eliminate existing complications and


Truncate is used to eliminate the tuples
fewer complications in the whole database from the
from the table.
table.

Integrity constraints get removed in the DROP Integrity constraint doesn’t get removed
command. in the Truncate command.

Since the structure exists, the View of


Since the structure does not exist, the View of the
the table exists in the Truncate
table does not exist in the Drop command.
command.

Drop query frees the table space complications from This query does not free the table space
memory. from memory.

It is fast as compared to the DROP


It is slow as there are so many complications
command as there are fewer
compared to the TRUNCATE command.
complications.

Read More: Differences between DROP and TRUNCATE Commands

SQL DROP AND TRUNCATE Statement Examples

Let’s look at some examples of the DROP and TRUNCATE statements in SQL and understand their
working:

let’s consider the given database Student_data:

Student Table
To create this table, write the following queries:

SQL

CREATE TABLE Student_details (

ROLL_NO INT,

NAME VARCHAR(25),

ADDRESS VARCHAR(25),

PHONE INT ,

AGE INT); --Inserting the data in Student Table

INSERT INTO Student_details(ROLL_NO,NAME,ADDRESS,PHONE,AGE) VALUES

(1,'Ram','Delhi',9415536635,24),

(2,'Ramesh','Gurgaon',9414576635,21),

(3,'Sujit','Delhi',9815532635,20),

(4,'Suresh','Noida',9115536695,21),

(5,'Kajal','Gurgaon',8915536735,28),

(6,'Garima','Rohtak',7015535635,23);

We will perform the examples on this particular table.

DROP Database Example

In this example, we will drop the student_data database.

Query:

DROP DATABASE student_data;

After running the above query whole database will be deleted.

DROP Table Example

In this example, we will drop the student_details table;

Query:

DROP TABLE student_details;

After running the above query whole table from the database will be deleted.

TRUNCATE Table Example

In this example, we will truncate the Student_details table from the student_data database.

Query:

TRUNCATE TABLE Student_details;


After running the above query Student_details table will be truncated, i.e, the data will be deleted
but the structure will remain in the memory for further operations.

Important Points About SQL DROP & TRUNCATE Statements

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.

Conclusion

In SQL, both DROP and TRUNCATE commands are used for removing data, but their impacts are
different. DROP is used when you want to completely remove a table or database, while TRUNCATE is
more efficient for removing all rows from a table without affecting its structure. Understanding when
and how to use these commands will help you maintain better control over your database and
optimize your database management processes.

SQL Query to Create a Backup Table

Last Updated : 28 Nov, 2024

Relational databases play an important role in managing data, especially during complex
operations like updates and deletions. To maintain data integrity, it is essential to back up
tables before making changes. SQL backup tables ensure the safety of the original dataset, allow
for data recovery, and facilitate safe experimentation.

This article explains the importance of backup tables, demonstrates various methods for creating
them in MySQL, PostgreSQL, and SQL Server, and highlights the limitations of common approaches.

Importance of Creating Backup Tables in SQL

Backup tables are essential during complex data changes or migrations because they let us safely
restore the original data if something goes wrong. Here are the key reasons why creating them is
essential:
 Data Integrity: Protecting the original dataset from accidental loss or corruption.

 Disaster Recovery: Ensuring that the data can be restored in case of failure or errors during
modifications.

 Safe Experimentation: Making changes to data without affecting the live dataset.

 Data Migration: Moving data from one system or table to another without losing original
records.

Demo Table: Student Information

We will be using the following table “Student Information” which consists of data of Geeks who
enrolled in our DSA course as shown below:

ID Age Student Name Sex

1 22 Harry Male

2 23 Vishal Male

3 20 Snehal Female

4 25 Ram Male

5 24 Hina Female

How to Create Backup Tables in SQL

We can create a backup of a table by creating a duplicate or copy of original database. This is
particularly useful for preserving the original table before performing updates, deletions, or other
modifications. Below is a detailed explanation of the syntax and terms used for this operation.

Syntax

CREATE TABLE Table_Name AS SELECT * FROM Source_Table_Name;

Key Terms

 Table_Name: Specifies the name of the new backup table.

 AS: Acts as an alias, enabling the SQL query to copy data from the source table into the
backup table.

Examples of SQL Backup Table Creation


Creating backup tables in SQL can involve duplicating all data, copying specific columns, or even
creating an empty table with the same structure. Let’s look at some examples on how
to copy/duplicate table in SQL to create a backup table in different scenarios:

1. Backup Table with All Columns and Data

In this example, we will create a backup table “stud_1” of “student_information” table by creating a
copy of “student_information” table that duplicates all columns and their data..

Query:

CREATE TABLE stud_1 AS SELECT * FROM student_information;


SELECT * FROM stud_1;

Query For Backup Table with All Columns Data

Output
SQL Backup Table with All Columns Data Example Output

2. SQL Backup Table with Specific Column Data Example

In this example, we create a backup table, “stud_2”, by copying only selected columns from
the “student_information” table using a SELECT statement.

Query:

CREATE TABLE stud_2 AS


SELECT id,student_name FROM student_information;
SELECT * FROM stud_2;
Query For Backup Table with Specific Column Data

Output

SQL Backup Table with Specific Column Data Example Output

Till now we have seen how to create a clone of the source table. In the above backup table, the
data is also copied along with the table. However, we can also create a backup table without copying
the data.

3. Backup Table Without Data


So, to create a table without any data being copied we can use the WHERE clause which needs to
return a FALSE value. For example, we can use WHERE 2<2 or WHERE 1=2.

In this example, we will create a backup table “geeks_student” of “student_information” table by


creating a copy of “student_information” table and copying its all columns without data.

Query:

CREATE TABLE geeks_student AS SELECT * FROM student_information


WHERE 1!=1;
SELECT * FROM geeks_student;

Query for Backup Table with No Data

Output
SQL Backup Table with No Data Example Output

4. Backup Table with Specific Columns and No Data

In this example, we will create a backup table “geek_student” of “student_information” table by


creating a copy of “student_information” table and copying specific columns without data.

Query:

CREATE TABLE specific_empty_backup AS


SELECT ID, Student_Name FROM student_information WHERE 1=2;
SELECT * FROM specific_empty_backup;

Query for Backup Table with Specific Columns and No Data

Output
SQL Backup Table with Specific Columns and No Data Example Output

Limitations of CREATE TABLE AS SELECT

While the CREATE TABLE AS SELECT statement is a convenient method for creating backup tables, it
has some limitations which are as follows:

 Constraints Are Not Copied: Constraints such as PRIMARY KEY, FOREIGN KEY, UNIQUE,
CHECK, and DEFAULT are not carried over to the new table.

 Indexes and Triggers Are Not Copied: Any indexes or triggers defined on the base table are
not included in the backup table.

 Manual Effort Required for Full Duplication: To replicate the full structure of the original
table, including constraints and indexes, you must manually define these elements after
creating the table.

How to Create Backup Tables with Constraints

To copy the structure of a table along with its constraints, the CREATE TABLE AS SELECT statement is
not sufficient. Instead, we need to define the table structure manually and then copy the data.

Example: Adding Constraints After Table Creation

1. Create a table without constraints:

CREATE TABLE student_backup AS SELECT * FROM student_information;

2. Add constraints to the backup table

ALTER TABLE student_backup ADD PRIMARY KEY (ID);


Example: Define Table with Constraints and Copy Data

1. Define the new table with constraints

CREATE TABLE student_backup (


ID INT PRIMARY KEY,
Age INT,
Student_Name VARCHAR(50),
Sex VARCHAR(10)
);

2. Copy data into the new table

INSERT INTO student_backup SELECT * FROM student_information;

Conclusion

Creating backup tables in SQL is an essential practice for ensuring data integrity, facilitating disaster
recovery, and enabling experimentation without compromising the original data. While the CREATE
TABLE AS SELECT statement is a quick and convenient method, it has limitations such as
the exclusion of constraints, indexes, and triggers. For a more complete backup, manual
intervention is required to replicate the full structure of the original table.

FAQs

How to make a backup table in SQL?

To create a backup table in SQL, use the CREATE TABLE statement with a SELECT * query to copy the
contents of the original table into a new one:
CREATE TABLE backup_table AS SELECT * FROM original_table;

How to create SQL backup?

In SQL, creating a backup involves using the database management system’s specific tools, such as
mysqldump for MySQL, or pg_dump for PostgreSQL. These tools generate a dump file of the
database or table: mysqldump -u username -p database_name > backup.sql

How do I save a created table in SQL?

To save a created table, simply use the CREATE TABLE statement to define its structure and data, then
execute the query. SQL databases automatically save the table when the statement is committed.
CREATE TABLE table_name (column1 datatype, column2 datatype,.);

What is Temporary Table in SQL?

Last Updated : 28 Nov, 2024

A temporary table in SQL is an important tool for maintaining intermediate results


during query execution. They help store temporary data without affecting the underlying permanent
tables.
In this article, we’ll explore temporary tables in SQL, their types (local vs. global), and how to use
them effectively in your database operations.

What Are Temporary Tables in SQL?

A temporary table in SQL is a special type of table that is created and stored in the system’s
temporary database (such as TempDB in SQL Server). This table is primarily used to store and
generate important mediation results when executing a query, stored procedure, or session.

Temporary tables are automatically deleted when the session or transaction that created them ends,
making them perfect for temporary or intermediate data storage. They are particularly useful in
situations where you need to perform calculations or data transformations without changing the
permanent database structure.

Syntax:

To Create a 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 the Temporary Table

SELECT * FROM #EmpDetails

Result:

id name

1 Lalit

2 Atharva

Types of Temporary Tables in SQL

There are 2 types of Temporary Tables: Local Temporary Table, and Global Temporary Table. These
are explained as following below.

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. Also, the user can drop this temporary table by using
the “DROP TABLE #EmpDetails” query. There will be Random Numbers are appended to the Name of
Table Name. If the Temporary Table is created inside the stored procedure, it get dropped
automatically upon the completion of stored procedure execution.

Example:

CREATE PROCEDURE ProcTemp


AS

BEGIN

CREATE TABLE #EmpDetails

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

SELECT * FROM #EmpDetails

END

EXECUTE ProcTemp

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. There will be
no random Numbers suffixed at the end of the Table Name.

Differences Between Local and Global Temporary Tables

Feature Local Temporary Table Global Temporary Table

Prefix # (Single hash) ## (Double hash)

Scope Only the session that created it Available to all sessions

Automatically dropped when the Dropped when the last connection


Lifetime
session ends referencing the table ends

Accessibilit Only the creating session can


All sessions can access it
y access it

Shared temporary data storage for multiple


Usage Session-specific data storage
sessions

Conclusion

Temporary tables in SQL are powerful tools for managing central data, performing complex
calculations, and improving query performance. Whether you use local temporary tables for session-
specific operations or global temporary tables to share data across multiple sessions, understanding
how to use these tables effectively will inform your database management processes simplified
Temporary tables for storing and manipulating data without impacting the permanent database
structure provide options , which make them ideal for tasks such as data manipulation, backup and
testing.

SQL ALTER TABLE

The SQL ALTER TABLE statement is a powerful tool that allows you to modify the structure of an
existing table in a database. Whether you’re adding new columns, modifying existing ones, deleting
columns, or renaming them, the ALTER TABLE statement enables you to make changes without losing
the data stored in the table.

In this article will learn about the ALTER TABLE statement with examples to demonstrate how it
works.

SQL ALTER TABLE STATEMENT

The ALTER TABLE statement in SQL is used to add, remove, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and remove various constraints on existing tables.

It allows for structural changes like adding new columns, modifying existing ones, deleting columns,
and renaming columns within a table.

Syntax:

To alter/modify the table use the ALTER TABLE syntax:

ALTER TABLE table_name

clause [column_name] [datatype];

Here, the clause is the operational clause of the ALTER TABLE statement. Some key clauses of the
ALTER TABLE statement are:

Common Use Cases for SQL ALTER TABLE

1. ADD – To add a new column to the table

The ADD clause is used to add a new column to an existing table. You must specify the name of the
new column and its data type.

Query:

ALTER TABLE table_name

ADD column_name datatype;

2. MODIFY/ALTER – To change the data type of an existing column

The MODIFY (or ALTER COLUMN in some databases like SQL Server) clause is used to modify the
definition of an existing column, such as changing its data type or size.

Query:

ALTER TABLE table_name

MODIFY COLUMN column_name datatype;

3. DROP – To delete an existing column from the table


The DROP clause allows you to remove a column from a table. Be cautious when using this command
as it will permanently remove the column and its data.

Query:

ALTER TABLE table_name

DROP COLUMN column_name;

4. RENAME COLUMN – To rename an existing column

You can rename an existing column using the RENAME COLUMN clause. This allows you to change
the name of a column while preserving its data type and content.

Query:

ALTER TABLE table_name

RENAME COLUMN old_name TO new_name;

5. RENAME TO – To rename the table itself

You can rename an entire table using the RENAME TO clause. This changes the name of the table
while preserving its structure and data.

ALTER TABLE table_name

RENAME TO new_table_name;

SQL ALTER TABLE Examples

Below are the examples of ALTER TABLE statement. These examples demonstrates different use cases
and shows how to use ALTER TABLE statement in SQL.

SQL ALTER TABLE ADD Column Example

The following SQL query adds an “Email” column to the “Students” table:

ALTER TABLE Students

ADD Email varchar(255);

SQL ALTER TABLE DROP Column Example

The following query deletes the “Email” column from “Students” table:

ALTER TABLE Students

DROP COLUMN Email;

SQL ALTER TABLE MODIFY Column Example

ALTER TABLE table_name

MODIFY COLUMN column_name datatype;

SQL ALTER TABLE Queries

Suppose there is a student database:


ROLL_N
O NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu

To ADD 2 columns AGE and COURSE to table Student.

Query:

ALTER TABLE Student ADD

(AGE number(3),COURSE varchar(40));

Output:

ROLL_NO NAME AGE COURSE

1 Ram

2 Abhi

3 Rahul

4 Tanu

MODIFY column COURSE in table Student.

Query:

ALTER TABLE Student

MODIFY COURSE varchar(20);

After running the above query the maximum size of the Course Column is reduced to 20 from 40.

DROP column COURSE in table Student.


Query:

ALTER TABLE Student

DROP COLUMN COURSE;

Output:

ROLL_NO NAME AGE

1 Ram

2 Abhi

3 Rahul

4 Tanu

Conclusion

The SQL ALTER TABLE statement is an essential tool for modifying the structure of an existing table.
Whether you need to add, delete, or modify columns, or even rename the table or columns, ALTER
TABLE provides the flexibility needed to manage your database schema efficiently. By following best
practices and using this command wisely, you can maintain the integrity and performance of your
database while making necessary structural changes.

You might also like