Engineering Full Stack Apps with Java and JavaScript
DDL stands for Data Definition Language, and these queries are used to create or manipulate the structure of the database and schemas. Here we will see basic DDL queries that you will use in general. Please feel free to add more through the comments section.
1. Create a database
CREATE DATABASE myDB;
2. Create a table mytable in a DB mydb, with two columns col1 of VARCHAR(20), col2 of INT, where col2 is the Primary Key.
CREATE TABLE mydb.mytable(
col1 VARCHAR(20), col2 INT PRIMARY KEY);
or
USE mydb;
CREATE TABLE mytable(
col1 VARCHAR(20), col2 INT PRIMARY KEY);
3. Create a user defined type
CREATE DISTINCT TYPE Euro AS DECIMAL(10,2);
4. Use check constraint along with create table to make sure the values stored in the length field are positive.
CREATE TABLE Items (Length INTEGER CHECK(length>0)));
5. Modify the type of a column
ALTER TABLE mytable MODIFY col1 VARCHAR(20) NOT NULL;
6. Rename a column
ALTER TABLE tablename RENAME COLUMN old_name TO new_name;
7. Add column to a table
ALTER TABLE mytable ADD( col2 VARCHAR(50), col3 INT);
8. Delete a column
ALTER TABLE table_name DROP COLUMN column_name;
9. Rename a table
ALTER TABLE table_name RENAME TO new_table_name;
10. Delete a table
DROP TABLE table_name
11. Create a new table by copying an old one.
SELECT * INTO Staff FROM Employees;
MySQL and Oracle uses a different syntax.
CREATE TABLE Staff AS SELECT * FROM Employees;