View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

    SQL Commands - A Comprehensive Guide

    Updated on 12/09/2024522 Views

    For years, I've explored the field of data analysis, and SQL has proven to be one of the most imperative tools. The language holds the key to unlocking the mysteries hidden in databases. I became fascinated by SQL commands as I learned more about them.

    Knowing SQL commands is invaluable, whether you're a seasoned web developer, an aspiring data analyst like myself, or simply interested in data organization. A broad range of data-related careers require proficiency in SQL commands.

    In this practical guide, I'll share my knowledge and give you an essential SQL commands cheat sheet. By the end, you will be confident in your ability to navigate and manipulate data within relational databases.

    Understanding Basic SQL Commands

    Before exploring specific SQL commands, it's crucial to establish a solid foundation in core database concepts.

    Relational Databases

    Relational databases keep data in structured tables with rows and columns. Each table represents a distinct entity or concept, while each column represents an entity's attribute.

    Data in these tables is linked together via relationships, which are frequently established using primary and foreign keys.

    Tables and Columns

    Tables are the fundamental components of a relational database. They function similarly to spreadsheets, with each row representing a unique record and each column representing a specific record attribute.

    For instance, a table named "Customers" might have columns for "CustomerID," "CustomerName," "Email," and "Phone number."

    Primary Keys and Foreign Keys

    Primary keys are unique identifiers for each row in a table. They ensure that no two rows contain the same data.

    Foreign keys are columns that refer to the primary key of another table. These relationships help to keep data integrity and consistency across multiple tables.

    Getting Started with Basic SQL Commands

    Now that we have a grasp of fundamental database concepts, let's explore some essential SQL commands that form the bedrock of data manipulation:

    1. SQL SELECT Statement

    The SQL SELECT statement is the cornerstone of retrieving data from a database table. Here's the basic syntax:

    SQL Commands

    SELECT column1, column2, ..., columnN

    FROM table_name;

    Example of SQL SELECT Statement

    SELECT CustomerID, CustomerName, Email

    FROM Customers;

    Output

    CustomerID

    Customer Name

    Email

    12452

    John Smith

    john.smith@email.com

    12596

    Jane Doe

    jane.doe@gmail.com

    12968

    Mike Jones

    mike.jones@hotmail.com

    The SQL SELECT statement retrieves the CustomerID, CustomerName, and Email columns from the Customers table. The output displays each record (row) of the table with the corresponding values for each column.

    2. Filtering Data with WHERE Clause

    You can filter the outcomes of a SELECT statement according to particular criteria by using the SQL WHERE statement. This is how the syntax looks:

    SQL Commands

    SELECT column1, column2, ..., columnN

    FROM table_name

    WHERE condition;

    The condition part specifies the criteria for filtering the data. You can use comparison operators like =, >, <, <> (not equal) and logical operators like AND, OR, and NOT to create complex filtering expressions.

    Example of a SQL WHERE statement

    SELECT CustomerID, CustomerName, Email

    FROM Customers

    WHERE Email LIKE '%@email.com';

    Output

    CustomerID

    Customer Name

    Email

    12452

    John Smith

    john.smith@email.com

    12368

    El Quinne

    el.quinne@email.com

    12128

    Tommy Tate

    tommy.tate@email.com

    The SQL WHERE statement retrieves all rows from the Customers table where the Email address ends with @email.com. The LIKE operator allows for pattern matching in the search criteria.

    3. SQL INSERT Command

    The SQL INSERT command adds new rows of data to a table. Here's the basic syntax:

    SQL Commands

    INSERT INTO table_name (column1, column2, ..., columnN)

    VALUES (value1, value2, ..., valueN);

    You specify the table name (table_name) followed by the columns (column1, column2, etc.) where you want to insert the new data. The VALUES clause provides the actual values to be inserted for each column.

    Example of SQL INSERT Command

    INSERT INTO Customers (CustomerID, CustomerName, Email)

    VALUES (12648, 'Alice Brown', 'alice.brown@email.com');

    The SQL INSERT command inserts a new record into the Customers table. It assigns the value 12648 to the CustomerID column, 'Alice Brown' to the CustomerName column, and 'alice.brown@email.com' to the Email column.

    Specifying Columns in INSERT Statement

    You must note that you can insert data into a specific subset of columns within a table. The order of the columns you specify in the SQL INSERT command must match the order of the values you provide in the VALUES clause.

    Example of SQL INSERT command

    INSERT INTO Customers (CustomerName, Email)

    VALUES ('David Lee', 'david.lee@email.com');

    4. SQL UPDATE Command

    The SQL UPDATE command lets you change the data that already exists in a table. The syntax is as follows:

    SQL Commands

    UPDATE table_name

    SET column1 = value1, column2 = value2, ..., columnN = valueN

    WHERE condition;

    You specify the table name (table_name) followed by the columns (column1, column2, etc.) that you want to update and their new values (value1, value2, etc.). The WHERE clause is optional but crucial for filtering the rows you want to update.

    Example of SQL UPDATE command

    UPDATE Customers

    SET Email = 'david.lee.updated@email.com'

    WHERE CustomerID = 12785;

    This SQL UPDATE command updates the Email address for the customer with CustomerID equal to 12785 in the Customers table. The WHERE clause ensures that only the specific record is modified.

    5. SQL DELETE Statement

    To delete rows from a table, use the SQL DELETE statement. The syntax is as follows:

    SQL Commands

    DELETE FROM table_name

    WHERE condition;

    You specify the table name (table_name) from which you want to delete rows. The WHERE clause, similar to the UPDATE statement, is optional and allows you to filter the rows you want to delete.

    Example of SQL UPDATE command

    DELETE FROM Customers

    WHERE Email LIKE '%@email.com';

    Any row in the Customers table where the email address ends in @email.com is deleted using this SQL DELETE statement. The DELETE statement erases data permanently, so use caution when using it.

    Advanced SQL Commands

    As you become comfortable with basic SQL commands, you can explore more advanced features to perform complex data manipulation tasks. Here are some key concepts to enhance your SQL skills:

    1. SQL JOIN Operations

    JOIN operations allow data from multiple tables to be combined based on a related column. This is essential for working with relational databases, where data is often distributed across different tables. Here are three types of SQL JOIN operations:

    1. An INNER JOIN retrieves only rows from both tables that have a matching value based on the join condition.
    2. A LEFT JOIN returns all rows from the left table and their corresponding rows from the right table. Rows in the left table that do not match in the right table will have NULL values in their columns.
    3. A RIGHT JOIN returns all rows from the right table and their corresponding rows from the left table. Rows in the right table that do not match any rows in the left table will have NULL values in the columns of the latter.

    2. Aggregate Functions

    Aggregate functions perform calculations on a data group and return a single summarized value. Here are some commonly used aggregate functions:

    • SUM(): Determines a numeric column's total.
    • AVG(): Determines a numeric column's average.
    • COUNT(): Determines how many rows in a table match a given condition or how many rows in the table total.
    • MIN(): Provides a column's lowest value.
    • MAX(): Returns a column's maximum value.

    3. Subqueries

    Subqueries are nested SELECT statements used within another SELECT statement to retrieve data based on a condition. They can be powerful for complex data filtering and manipulation.

    There are two main types of subqueries:

    Nested SELECT Statements: A subquery can be embedded within the WHERE clause of another SELECT statement.

    Correlated Subqueries: A correlated subquery references data from the outer query in its WHERE clause.

    4. Transaction Control: COMMIT and ROLLBACK

    Maintaining data integrity is paramount when working with databases. This is where transaction control commands, specifically COMMIT and ROLLBACK, become crucial.

    A transaction is a set of SQL statements functioning as a single unit of work. It could involve inserting new data, updating existing records, or deleting entries. COMMIT acts like a confirmation, permanently saving all the changes within the transaction. Once you COMMIT, these updates become the official state of the database.

    However, if errors arise or you decide to abandon the changes mid-transaction, ROLLBACK serves as a safety net. It reverses all the modifications within that specific transaction, essentially restoring the database to its state before you begin.

    Example

    Let's consider an e-commerce scenario where you need to deduct the order amount from a customer's balance after a successful purchase. Here's how to ensure data integrity:

    START TRANSACTION;

    -- Update customer balance (assuming a 'Balance' column)

    UPDATE Customers

    SET Balance = Balance - OrderAmount

    WHERE CustomerID = <customer_id>;

    -- Insert new order record

    INSERT INTO Orders (CustomerID, OrderAmount)

    VALUES (<customer_id>, <order_amount>);

    COMMIT;

    This code ensures that the new order record is only inserted if the customer balance update is successful (no errors). If any error occurs during the update, a ROLLBACK will be issued, preventing inconsistencies in the data.

    Data Definition Language (DDL) Commands

    DDL statements are used to define and manipulate the structure of the database, such as creating, modifying, and deleting tables. Here are some essential DDL commands:

    1. SQL CREATE TABLE Statement

    The SQL CREATE TABLE statement defines the structure of a new table, specifying the columns (attributes) and their data types. Here's the syntax:

    SQL Commands

    CREATE TABLE table_name (

    column1 data_type,

    column2 data_type,

    ...,

    columnN data_type

    );

    You specify the table name (table_name) followed by a list of columns (column1, column2, etc.) and their corresponding data types. Data types define the kind of data each column can hold, such as integers, strings, dates, etc.

    Example of SQL CREATE TABLE statement

    CREATE TABLE Customers (

    CustomerID INT PRIMARY KEY AUTO_INCREMENT,

    CustomerName VARCHAR(50) NOT NULL,

    Email VARCHAR(100) UNIQUE,

    Phone VARCHAR(20)

    );

    This SQL CREATE TABLE statement creates a Customer table with four columns:

    • CustomerID: An integer set as the primary key with auto-increment.
    • CustomerName: A string (varchar) with a maximum length of 50 characters cannot be null (empty).
    • Email: A unique string (varchar) with a maximum length of 100 characters.
    • Phone: A string (varchar) with a maximum length of 20 characters.

    2. SQL ALTER TABLE Command

    The SQL ALTER TABLE command allows you to modify the structure of an existing table. Here are some common modifications:

    • Adding new columns
    • Modifying existing column data types
    • Dropping columns
    • Renaming columns

    Example of SQL ALTER TABLE command

    ALTER TABLE Customers ADD Country VARCHAR(50);

    This SQL ALTER TABLE command adds a column named Country of type string (varchar) with a maximum length of 50 characters to the Customers table.

    3. SQL DROP TABLE Statement

    The SQL DROP TABLE statement removes a table from the database. Use caution with this statement, as it permanently deletes the table and its data.

    Example of SQL DROP TABLE statement

    DROP TABLE Orders;

    This SQL DROP TABLE statement deletes the Orders table from the database.

    Common Errors and How to Avoid Them

    As you work with SQL commands, you might encounter errors. Here are some common types of errors and how to prevent them:

    • Syntax Errors: These errors occur when the SQL statement is grammatically incorrect. Double-check your code for typos, missing keywords, or incorrect punctuation.
    • Logical Errors: These errors occur when the logic behind your statement is flawed, even though the syntax might be correct. Analyze your query carefully and ensure it retrieves or manipulates data as intended.
    • Runtime Errors: These errors occur during execution due to data type mismatches or referencing non-existent tables. Ensure your data types are compatible, and double-check table and column names.

    By carefully reviewing your code and understanding the purpose of each statement, you can minimize errors and write effective SQL queries.

    Conclusion

    This comprehensive guide explored essential SQL commands, from fundamental data retrieval to advanced concepts like joins, aggregate functions, and subqueries. We've also covered Data Definition Language (DDL) commands for creating and modifying database tables.

    By actively engaging in these steps, you'll transform into a confident SQL user. Remember, mastery requires dedication and consistent practice. Keep exploring SQL's vast potential—the world of data awaits your insightful queries!

    Frequently Asked Questions (FAQs)

    1. What are the five basic SQL commands?

    The five basic SQL commands are:

    • SELECT: Retrieves data from a table.
    • INSERT: Inserts new data into a table.
    • UPDATE: Modifies existing data in a table.
    • DELETE: Removes data from a table.
    • WHERE: Filters data based on a specific condition.

    2. How do you write SQL commands?

    SQL commands use a specific syntax that includes keywords, clauses, and operators. It is critical that you use the correct syntax for each command you wish to execute.

    3. What's the difference between DDL and DML commands?

    DDL (Data Definition Language): These commands define and manipulate the database structure, such as creating, modifying, and deleting tables.

    DML (Data Manipulation Language): These commands manipulate data in existing tables.

    4. What is the syntax for a SQL command?

    The syntax of a SQL command varies according to the command being used. However, most SQL commands have a standard structure that includes keywords, clauses, and operators.

    5. How do you run a SQL command?

    SQL commands are typically executed with a database management system (DBMS) or another tool that allows you to interact with the database. These tools may have a graphical user interface or a command-line interface, allowing you to write and execute SQL queries.

    6. Can SQL commands be combined?

    Yes, SQL commands can be combined to perform more complex data manipulation tasks. For example, you can filter data using a SELECT statement with a WHERE clause and then use an aggregate function such as SUM() to calculate total sales for a specific product category.

    7. What is the purpose of the COMMIT and ROLLBACK commands?

    COMMIT command permanently saves the changes you made to the database following a series of SQL statements.

    ROLLBACK command undoes all changes made since the previous COMMIT statement, returning the database to its original state.

    8. Can SQL commands be used to restrict access to data?

    Yes, database management systems support access control through mechanisms such as roles and permissions.

    9. Are SQL commands case-sensitive?

    SQL commands' case sensitivity varies depending on the database management system being used. It's always a good idea to consult the documentation for your specific database system to confirm its case-sensitivity policies.

    10. Is it TRUNCATED DDL or DML?

    Truncate is classified as a DDL (Data Definition Language) operation. It deletes all rows from a table, but unlike DELETE, it does not target specific data and simply resets the storage allocation.

    upGrad Learner Support

    Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

    text

    Indian Nationals

    1800 210 2020

    text

    Foreign Nationals

    +918068792934

    Disclaimer

    1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

    2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.