MS SQL Server – Alter Database & Table

In Microsoft SQL Server, you can use the ALTER DATABASE and ALTER TABLE statements to modify the structure and properties of databases and tables, respectively. Here’s a brief overview of how to use these statements:

ALTER DATABASE:

  1. Modifying Database Properties:
    • You can use ALTER DATABASE to modify various database-level properties such as collation, compatibility level, and database options.
    • Example: Changing the database collation:ALTER DATABASE YourDatabaseName COLLATE NewCollation;
  2. Setting Database Options:
    • ALTER DATABASE allows you to configure database options like recovery model, auto shrink, and file growth settings.
    • Example: Changing the recovery model to “FULL”:ALTER DATABASE YourDatabaseName SET RECOVERY FULL;
  3. Adding and Modifying Files:
    • You can add new data or log files to a database and modify file properties using ALTER DATABASE.
    • Example: Adding a new data file:ALTER DATABASE YourDatabaseName ADD FILE ( NAME = NewDataFile, FILENAME = 'C:\Path\To\DataFile.ndf', SIZE = 10MB, MAXSIZE = UNLIMITED, FILEGROWTH = 5MB );
  4. Changing Database Owner:
    • You can change the owner of a database using the ALTER DATABASE statement.
    • Example: Changing the database owner to a new user or role:ALTER DATABASE YourDatabaseName SET OWNER TO NewOwner;

ALTER TABLE:

  1. Adding Columns:
    • You can use ALTER TABLE to add new columns to an existing table.
    • Example: Adding a new column to the “Employees” table:ALTER TABLE Employees ADD NewColumn INT;
  2. Modifying Columns:
    • ALTER TABLE allows you to modify column properties, such as data type, constraints, and nullability.
    • Example: Changing the data type of an existing column:ALTER TABLE YourTableName ALTER COLUMN YourColumn VARCHAR(100);
  3. Dropping Columns:
    • You can remove columns from a table using ALTER TABLE.
    • Example: Dropping a column from the “Products” table:ALTER TABLE Products DROP COLUMN ColumnToDelete;
  4. Adding Constraints:
    • You can add constraints (e.g., primary key, unique, foreign key) to existing tables.
    • Example: Adding a unique constraint to a column:ALTER TABLE YourTableName ADD CONSTRAINT UniqueConstraintName UNIQUE (ColumnName);
  5. Dropping Constraints:
    • Similarly, you can remove constraints from a table.
    • Example: Dropping a foreign key constraint:ALTER TABLE Orders DROP CONSTRAINT ForeignKeyName;

ALTER DATABASE and ALTER TABLE statements are powerful tools for making changes to your database schema and properties without the need to recreate the entire database or table. However, when using these statements, exercise caution to avoid unintended data loss or corruption, especially in a production environment. It’s a good practice to test any schema changes in a development or staging environment first.