T-SQL Tutorial

T-SQL DDL(Data Definition Language)


This article shows how to use DDL(Data Definition Language) statements.
Uses DDL statements to create, alter, or drop objects in a SQL Server database.
The objects of a database are: schemas, tables, views, stored procedures, users, indexes, constraints, triggers, user-defined functions and types, roles, global variables.



CREATE

The CREATE statement is used to create new objexts in a SQL Server database.

The keyword CREATE DATABASE is the T-SQL statement that is used to create a new database.

CREATE DATABASE test_database;

The CREATE SCHEMA statement is used to create a new schema in the current SQL Server database.

CREATE SCHEMA test_schema;

The CREATE USER statement is used to create a new user database.

CREATE USER user_test WITH PASSWORD = user_pass;

To create a table in a SQL Server database, use the CREATE TABLE command.

CREATE TABLE books(id int, name varchar(100), price int);

To create a view in SQL Server database uses CREATE VIEW statement.

CREATE VIEW view_books as SELECT * FROM books;

The command CREATE INDEX is used to create a index on table column.

CREATE INDEX p_index ON books (price);

ALTER

The ALTER statement is used to alter a SQL Server database.
The T-SQL ALTER statement uses to change table names, add new columns to a table, delete or rename columns in a table.
ALTER is also used to modify views, storage procedures, triggers, indexes.

ALTER DATABASE test_database;
ALTER TABLE books ADD book_date time;
ALTER TABLE books DROP COLUMN book_date;
ALTER VIEW view_books as SELECT * FROM books WHERE price > 50;
ALTER INDEX p_index ON books REBUILD;
ALTER INDEX ALL ON books REBUILD;
ALTER INDEX p_index ON books DISABLE;


DROP

The DROP statement is used to drop a SQL Server database.
The T-SQL DROP statement is used to delete objects from the database, objects such as: schemas, tables, views, storage procedures, indexes, users, roles, triggers.
ALTER is also used to modify views, storage procedures, triggers, indexes.

DROP DATABASE test_database;
DROP SCHEMA test_schema;
DROP USER test_user;
DROP INDEX books.p_index;
DROP VIEW view_books;
DROP TABLE books;
DROP TRIGGER test_trigger;
DROP PROCEDURE test_procedure;


TRUNCATE TABLE

The TRUNCATE TABLE statement is used to delete all rows from a table.

TRUNCATE TABLE test_table;