SQL Queries

This pages illustrates details associated with Create, Update and Delete structured and relation data.

SQL commands

These are essential for managing and manipulating databases effectively. They are categorized into two main types, each serving specific purposes in database operations. There are other three minor types that are usually managed by the database administrator.

  1. Data Definition Language (DDL):

    • DDL commands are used to define and modify the structure of database objects such as tables, indexes, and schemas. Changes made through DDL commands are automatically committed to the database.

    • Common DDL Commands:

      • CREATE: Creates new database objects (e.g., tables, databases).

        CREATE TABLE Employees (ID INT, Name VARCHAR(255));
      • ALTER: Modifies existing database objects.

        ALTER TABLE Employees ADD COLUMN Address VARCHAR(255);
      • DROP: Deletes existing database objects.

        DROP TABLE Employees;
      • TRUNCATE: Removes all records from a table but retains the table structure.

        TRUNCATE TABLE Employees;
  2. Data Manipulation Language (DML):

    • DML commands are used for manipulating data within existing tables. This includes inserting, updating, and deleting records.

    • Common DML Commands:

      • INSERT: Adds new records to a table.

        INSERT INTO Employees (ID, Name) VALUES (1, 'John Doe');
      • UPDATE: Modifies existing records.

        UPDATE Employees SET Name = 'Jane Doe' WHERE ID = 1;
      • DELETE: Removes records from a table.

        DELETE FROM Employees WHERE ID = 1;
  3. Data Query Language (DQL):

    • DQL is primarily concerned with querying data from the database. The main command in this category is SELECT.

    • Common DQL Command:

      • SELECT: Retrieves data from one or more tables.

        SELECT Name FROM Employees WHERE ID = 1;
  4. Data Control Language (DCL):

    • DCL commands manage user permissions and access controls within the database system.

    • Common DCL Commands:

      • GRANT: Assigns privileges to users.

        GRANT SELECT ON Employees TO UserName;
      • REVOKE: Removes previously granted privileges.

        REVOKE SELECT ON Employees FROM UserName;
  5. Transaction Control Language (TCL):

    • TCL commands manage transactions within the database, ensuring that a series of operations are completed successfully or rolled back if an error occurs.

    • Common TCL Commands:

      • COMMIT: Saves all changes made in the current transaction.

      • ROLLBACK: Undoes changes made in the current transaction if an error occurs.

These SQL command types collectively enable users to create, manipulate, query, and control access to data in relational databases, forming the backbone of effective database management systems.

Commands in Detail

SELECT

The SQL SELECT statement is a powerful tool used to retrieve data from databases. It can be utilized in various forms, each serving different purposes. Here are the main types of SELECT statements:

  1. Basic SELECT Statement:

    • Retrieves specific columns from a table.

  2. SELECT All Columns:

    • Uses an asterisk (*) to select all columns from a table.

  3. SELECT with WHERE Clause:

    • Filters records based on specified conditions.

  4. SELECT with ORDER BY Clause:

    • Sorts the result set by one or more columns.

  5. SELECT with GROUP BY Clause:

    • Groups rows that have the same values in specified columns into summary rows.

  6. SELECT with HAVING Clause:

    • Filters groups created by GROUP BY based on specified conditions.

  7. SELECT with JOINs:

    • Combines rows from two or more tables based on related columns.

    • INNER JOIN: Returns records with matching values in both tables.

    • LEFT JOIN: Returns all records from the left table and matched records from the right table.

  8. SELECT with DISTINCT:

    • Returns unique values from a specified column.

  9. SELECT with Subqueries:

    • A nested query that retrieves data based on results from another query.

  10. SELECT INTO Statement:

    • Copies data from one table into another new table.

INSERT

The SQL INSERT statement is essential for adding new records to a database table. There are several types of INSERT statements, each serving different purposes. Here’s a comprehensive overview:

  1. Single Row Insert:

    • This is the most basic form of the INSERT statement, used to add a single row to a table.

    • Syntax:

  2. Insert Without Specifying Columns:

    • You can insert data without specifying the column names if you provide values for all columns in the correct order.

    • Syntax:

  3. Multi-Row Insert:

    • This allows you to insert multiple rows in a single INSERT statement, which can improve performance.

    • Syntax:

  4. Insert Using SELECT Statement:

    • You can insert data into a table by selecting it from another table. This is useful for copying data.

    • Syntax:

  5. Insert with Default Values:

    • If you want to insert a row and use default values for certain columns, you can specify DEFAULT for those columns.

    • Syntax:

  6. Insert with ON DUPLICATE KEY UPDATE (MySQL specific):

    • This allows you to update existing records if a duplicate key violation occurs during the insert operation.

    • Syntax:

  7. Insert with RETURNING Clause (PostgreSQL specific):

    • This allows you to return values from the inserted row(s), which is useful for obtaining auto-generated keys.

    • Syntax:

CREATE

The CREATE statement in SQL is primarily used to create database objects such as tables, indexes, views, and types. Here’s a comprehensive overview of the various types of CREATE statements:

  1. CREATE TABLE:

    • This statement is used to create a new table in the database. You define the table name, columns, and their data types.

    • Syntax:

    • Example:

  2. CREATE TABLE AS:

    • This creates a new table based on the result of a SELECT query from an existing table.

    • Syntax:

    • Example:

ALTER

The ALTER statement in SQL is used to modify the structure of an existing database object, primarily tables. Here are the various types of ALTER statements:

  1. ALTER TABLE - ADD Column:

    • This command adds one or more new columns to an existing table.

    • Syntax:

    • Example:

  2. ALTER TABLE - DROP Column:

    • This command removes one or more columns from a table.

    • Syntax:

    • Example:

  3. ALTER TABLE - MODIFY/ALTER Column:

    • This command changes the data type or constraints of an existing column.

    • Syntax for MySQL/Oracle:

    • Syntax for SQL Server:

    • Example:

  4. ALTER TABLE - RENAME Column:

    • This command renames an existing column in a table.

    • Syntax (varies by database):

    • Example (for PostgreSQL):

  5. ALTER TABLE - RENAME Table:

    • This command changes the name of an existing table.

    • Syntax:

    • Example:

  6. ALTER TABLE - ADD CONSTRAINT:

    • This command adds a new constraint (e.g., primary key, foreign key) to an existing table.

    • Syntax:

    • Example:

  7. ALTER TABLE - DROP CONSTRAINT:

    • This command removes an existing constraint from a table.

    • Syntax:

    • Example:

These ALTER statements provide flexibility in modifying database structures as requirements evolve, ensuring that databases can adapt to changing needs without requiring complete redesigns.

DROP vs DELETE

In SQL, both the DELETE and DROP commands are used to remove data, but they serve distinct purposes and operate at different levels. Here’s a detailed comparison of the two:

DELETE Command

  • Purpose: The DELETE command is used to remove specific rows from a table based on a condition. It allows for selective deletion of data while preserving the table structure.

  • Type: It is classified as a Data Manipulation Language (DML) command.

  • Syntax:

  • Rollback Capability: Actions performed using DELETE can be rolled back, meaning you can restore deleted rows if needed, as it maintains a transaction log.

  • Triggers: The DELETE command can activate triggers defined on the table, allowing for additional actions to occur automatically upon deletion.

  • Performance: The performance of DELETE may be slower, especially when removing many rows, as it processes each row individually.

DROP Command

  • Purpose: The DROP command is used to completely remove an entire database object, such as a table or database, along with all its data and structure. Once executed, the object cannot be recovered unless a backup exists.

  • Type: It is classified as a Data Definition Language (DDL) command.

  • Syntax:

  • Rollback Capability: Actions performed using DROP cannot be rolled back; they are permanent and immediate.

  • Triggers: The DROP command does not activate any triggers since it removes the entire object from the database.

  • Performance: The DROP command is generally faster than DELETE because it does not need to process individual rows; it simply removes the entire structure.

UPDATE

The SQL UPDATE statement is used to modify existing records in a table. It allows for updating single or multiple columns for one or more rows based on specified conditions. Here are the various types of UPDATE statements:

  1. Basic UPDATE Statement:

    • This is used to update specific columns in a single row based on a condition.

    • Syntax:

    • Example:

  2. UPDATE Multiple Columns:

    • You can update multiple columns in a single UPDATE statement.

    • Syntax:

    • Example:

  3. UPDATE Multiple Rows:

    • This updates all rows that meet a specified condition.

    • Syntax:

    • Example:

  4. UPDATE Without WHERE Clause:

    • If the WHERE clause is omitted, all records in the table will be updated. This should be used with caution.

    • Example:

  5. UPDATE Using Subquery:

    • You can use a subquery to determine the values to be updated based on data from another table.

    • Syntax:

    • Example:

  6. UPDATE with JOIN (in some SQL dialects):

    • This allows you to update records in one table based on matching records in another table.

    • Syntax (for SQL Server):

    • Example:

  7. Conditional Updates with CASE Statement:

    • You can use a CASE statement within an UPDATE to set different values based on conditions.

    • Syntax:

    • Example:

These various forms of the UPDATE statement provide flexibility in modifying data within SQL databases, allowing users to perform targeted changes efficiently while maintaining data integrity. Always ensure that conditions are correctly specified to avoid unintended updates, especially when omitting the WHERE clause.

Sample Queries for Review

Last updated