SQL (Structured Query Language) is used to work with databases. It helps you create, change, get, and delete data, as well as control transactions and user access. SQL commands are divided into five main types: DDL, DML, DQL, TCL, and DCL. So, this guide will explain these commands clearly and give examples. As well as this guide will also offer tips on how to use SQL effectively to improve database performance and management.

What are SQL Commands?

SQL commands are simple instructions to interact with a database. They help you retrieve, add, update, or delete data. As well as they help in managing tasks like creating tables or setting permissions, making them essential for handling databases.

Types of SQL Commands

SQL commands can be broadly categorized into five main types based on their functionality. So, here is a summary:

sql-commands-types

1. Data Definition Language (DDL)

DDL commands in SQL are used to define and manage database structure and schema.

  • Commands:
    • CREATE: Create new databases, tables, or objects.
      Example: CREATE TABLE employees (id INT, name VARCHAR(100));
    • ALTER: Modify existing database objects.
      Example: ALTER TABLE employees ADD COLUMN age INT;
    • DROP: Delete existing databases or objects.
      Example: DROP TABLE employees;
    • TRUNCATE: Remove all rows from a table without logging individual row deletions.
      Example: TRUNCATE TABLE employees;

2. Data Manipulation Language (DML)

DML SQL commands are used to manipulate data within tables.

  • Commands:
    • INSERT: Add new data into a table.
      Example: INSERT INTO employees (id, name) VALUES (1, 'John Doe');
    • UPDATE: Modify existing data in a table.
      Example: UPDATE employees SET name = 'Jane Doe' WHERE id=1;
    • DELETE: Remove data from a table.
      Example: DELETE FROM employees WHERE id=1;

3. Data Query Language (DQL)

Used to retrieve data from the database.

  • Command:
    • SELECT: Fetch data from one or more tables.
      Example: SELECT name FROM employees WHERE id=1;

4. Transaction Control Language (TCL)

Used to manage transactions in the database.

  • Commands:
    • COMMIT: Save all changes made by the transaction.
      Example: COMMIT;
    • ROLLBACK: Undo changes made by the transaction.
      Example: ROLLBACK;
    • SAVEPOINT: Set a point within a transaction to roll back to.
      Example: SAVEPOINT sp1;
    • SET TRANSACTION: Define properties for a transaction.
      Example: SET TRANSACTION READ ONLY;

5. Data Control Language (DCL)

DCL commands in SQL are used to control access to data in the database.

  • Commands:
    • GRANT: Provide access or privileges to users.
      Example: GRANT SELECT ON employees TO user1;
    • REVOKE: Remove access or privileges from users.
      Example: REVOKE SELECT ON employees FROM user1;

Important SQL Commands List

Here is a quick overview of SQL commands that are essential for database management:

1. CREATE

The CREATE statement is used to define a new table, database, or other database objects (like views, indexes, etc.).

Example:

-- Creating a new database

CREATE DATABASE School;

-- Creating a new table

CREATE TABLE Students (

StudentID INT PRIMARY KEY,

Name VARCHAR(100),

Age INT,

Grade CHAR(1)

);

Explanation:

  • The first CREATE statement creates a new database named School.
  • The second CREATE statement creates a table Students with columns StudentID, Name, Age, and Grade.
    • StudentID is defined as the primary key to ensure each student has a unique identifier.
    • VARCHAR(100) specifies a string column with a maximum of 100 characters.
    • CHAR(1) is used for single-character data, like a grade.

2. SELECT

The SELECT statement retrieves data from one or more tables.

Example:

-- Retrieving all columns and rows

SELECT * FROM Students;

-- Retrieving specific columns

SELECT Name, Grade FROM Students WHERE Age > 18;

Explanation:

  • The first SELECT SQL commands retrieve all columns and rows from the Students table.
  • The second SELECT retrieves only the Name and Grade columns where the Age of students is greater than 18.
    • The * symbol is used to select all columns.
    • The WHERE clause filters the rows based on the condition.

3. INSERT

The INSERT statement is one of the SQL basic commands. Which is used to add records to a table.

Example:

-- Adding a new student to the table

INSERT INTO Students (StudentID, Name, Age, Grade)

VALUES (1, 'Alice Johnson', 20, 'A');

-- Adding multiple students

INSERT INTO Students (StudentID, Name, Age, Grade)

VALUES 

(2, 'Bob Smith', 19, 'B'),

(3, 'Cathy Brown', 18, 'A');

Explanation:

  • The first INSERT adds a single record to the Students table.
  • The second INSERT adds multiple records in one statement.

4. UPDATE

The UPDATE statement modifies existing data in a table.

Example:

-- Updating a student's grade

UPDATE Students

SET Grade = 'B'

WHERE StudentID = 1;

-- Updating multiple rows

UPDATE Students

SET Grade = 'A'

WHERE Age > 18;

Explanation:

  • The first UPDATE modifies the Grade of the student with StudentID = 1 to B.
  • The second UPDATE modifies the grades of all students older than 18 to A.
  • The WHERE clause ensures only specific rows are updated.

5. DELETE

The DELETE statement removes records from a table.

Example:

-- Deleting a specific student

DELETE FROM Students

WHERE StudentID = 3;

-- Deleting all students

DELETE FROM Students;

Explanation:

  • The first DELETE removes the student with StudentID = 3 from the Students table.
  • The second DELETE removes all rows from the table. Be cautious as this action is irreversible.

6. DROP

The DROP statement is used to delete tables, databases, or other objects entirely.

Example:

-- Dropping a table

DROP TABLE Students;

-- Dropping a database

DROP DATABASE School;

Explanation:

  • The first DROP deletes the Students table, including all its data and structure.
  • The second DROP deletes the School database entirely. Use this command with caution, as it permanently removes the object and all associated data.

Each of these SQL commands examples serves a distinct purpose in managing and manipulating database structures and data. Use them carefully, especially DELETE and DROP, as they result in permanent data loss.

Best Practices for Using SQL Commands

Using SQL effectively requires understanding its capabilities, structure, and potential pitfalls. Here are some best practices for writing and executing SQL commands:

1. General Best Practices

  • Understand Your Database Schema
      • Familiarise yourself with table structures, relationships, indexes, and constraints before writing queries.
  • Use Descriptive Names
      • Use meaningful table and column names to make queries easier to read and maintain.
  • Be Explicit
      • Use fully qualified table names (schema.table) and specify column names instead of using SELECT *.
  • Comment Your Code
    • Add comments to explain complex queries for future reference and team collaboration.

2. Query Optimization

  • Minimise SELECT *
      • Fetch only the columns you need to reduce data transfer and improve performance.
  • Use Indexes Wisely
      • Leverage indexes for faster retrieval, but avoid over-indexing as it may slow down write operations.
  • Limit Rows Returned
      • Use LIMIT or TOP clauses to restrict the number of rows returned in large datasets.
  • Optimise Joins
      • Ensure proper use of INNER, LEFT, RIGHT, and FULL joins. Analyse join order for efficiency.
  • Filter Early
      • Apply filters using WHERE or HAVING clauses as early as possible to reduce the result set.
  • Avoid Duplicate Data
    • Use DISTINCT judiciously; it can be computationally expensive. Design queries to avoid duplicates upfront.

3. Write Maintainable Code

  • Use Aliases
      • Use table aliases to simplify long table names and improve readability.
      • Example: SELECT c.name FROM customers AS c
  • Break Complex Queries
      • Break complex queries into Common Table Expressions (CTEs) or subqueries for clarity and reuse.
  • Normalise and Denormalize Appropriately
    • Normalise tables for minimal redundancy but denormalize when performance gains outweigh storage costs.

4. Security Best Practices

  • Prevent SQL Injection
      • Use parameterized structured query language commands or prepared statements to avoid malicious input execution.
  • Limit Permissions
      • Grant users only the necessary permissions (e.g., SELECT, INSERT) to minimize security risks.
  • Sanitize Input
      • Validate and sanitize all user inputs before including them in SQL commands.
  • Avoid Storing Sensitive Data Plaintext
    • Encrypt sensitive data (e.g., passwords, personal details) before storing it in the database.

5. Testing and Debugging

  • Test Queries
      • Run queries in a test environment to ensure they behave as expected without affecting production data.
  • Use Explain Plans
      • Use EXPLAIN or EXPLAIN PLAN to analyze query execution paths and identify bottlenecks.
  • Log Queries
    • Log slow-running queries and optimize them based on execution metrics.

6. Version Control and Collaboration

  • Track Changes
      • Use version control (e.g., Git) to track changes in SQL scripts and schemas.
  • Standardise Formatting
      • Agree on SQL formatting conventions (e.g., capitalization of keywords, indentation) within your team.
  • Use Stored Procedures and Views
    • Encapsulate frequently used logic in stored procedures or views for easier maintenance.

Advanced Tips for SQL Optimization

Here are some advanced tips for optimizing SQL commands or queries to enhance performance:

1. Understand Query Plans

  • Use EXPLAIN to see how your query is executed and find slow steps.
  • Make sure key columns have indexes and are being used in the plan.
  • Split big tables into partitions to scan less data.

2. Optimize Joins

  • Start joins with smaller tables to reduce extra work.
  • Use INNER JOIN if you don’t need unmatched rows.
  • Ensure join columns have indexes.
  • Use hash joins for large, non-indexed tables.

3. Process Less Data

  • Avoid SELECT *; pick only the columns you need.
  • Use WHERE to filter rows early.
  • Use LIMIT, TOP, or FETCH to fetch fewer rows.

4. Improve Subqueries

  • Replace subqueries that run for every row with JOINs.
  • Use Common Table Expressions (CTEs) for easier and reusable queries.

5. Index Smartly

  • Use multi-column indexes for queries with multiple filters.
  • Include all columns in SELECT and WHERE in your index (covering index).
  • Rebuild indexes regularly to fix fragmentation.

6. Refactor Queries

  • Combine tables (denormalize) to avoid too many joins if you read data often.
  • Use materialized views to save precomputed results.
  • Use temporary tables for repeated intermediate results.

7. Use Database Features

  • Add hints to guide the database on how to execute queries.
  • Cache SQL commands query results for frequent, similar queries.
  • Use parallel processing for big queries.
  • Wrap complex logic in stored procedures for efficiency.

8. Group and Aggregate Smarter

  • Precompute summaries in separate tables if you need them often.
  • Filter raw data first with WHERE before grouping and using HAVING.

9. Optimize Storage

  • Use clustered indexes to keep related data close together.
  • For reporting systems, use columnar storage for faster aggregations.
  • Compress data to save space and improve read performance.

10. Streamline Transactions

  • Process large changes in smaller chunks.
  • Pick a transaction isolation level that’s fast but still correct.

11. Avoid Common Mistakes

  • Don’t wrap columns in functions (e.g., UPPER(column)) in WHERE clauses; it prevents index use.
  • Use the same data types in comparisons to avoid extra processing.

12. Monitor and Test

  • Use tools to find slow queries (e.g., MySQL slow log, PostgreSQL stats).
  • Check CPU, memory, and disk usage for problems.
  • Test one change at a time to measure improvement.

SQL commands are essential for managing and optimizing databases, forming the foundation of data-driven decision-making. If you're eager to master SQL and its role in data analysis, our Data Analytics Course is perfect for you. Learn to query, manage, and analyze data to uncover valuable insights and drive business success.

Conclusion

In conclusion, learning SQL commands is key to managing and improving databases. DDL commands help you create and change structures, DML commands let you modify data, and DQL commands help you retrieve it. TCL commands control transactions, and DCL commands manage user access. By following best practices and using optimization tips, you can make your queries faster and your database more efficient. Whether you're building or improving a database, these commands will help you do it better. Keep practicing and learning to stay updated in the world of SQL.

Frequently Asked Questions (FAQs)
Q. How to delete tables in SQL?

Ans. To delete a table in SQL, use the DROP TABLE command. It generally removes the table and all its data permanently, and you can't undo this action.

Q. What are the 5 basic SQL commands?

Ans. The five basic SQL commands are: CREATE (to make tables or databases), and SELECT (to get data). As well as INSERT (to add data), UPDATE (to change data), and DELETE (to remove data).