SQL Essentials for Students
SQL Essentials for Students
Syllabus:
Introduction of SQL, features of SQL, Data Definition & Data Manipulation commands in SQL, SQL operators, Update State-
ments & Views in SQL, Query & Sub query, Data Retrieval Queries & Data Manipulation Statements examples etc. Overview
of Tuple Oriented Calculus & Domain Oriented Relational Calculus.
1     Introduction of SQL
SQL (Structured Query Language) is a programming language used to manage and manipulate relational databases. It is a
standard language for managing data in a database, and it provides an easy and efficient way to access, store, and retrieve data.
SQL is used by database administrators, data analysts, and software developers to create, modify, and manage databases.
   SQL is a declarative language, which means that users can describe the data they want to retrieve or manipulate, and the
database management system (DBMS) will figure out how to do it. SQL is a domain-specific language, which means that it is
designed for a specific purpose (in this case, working with databases).
                                                                1
    1.3     SQL Constraints
    SQL constraints are rules and conditions applied to columns in a database table to ensure data integrity and maintain consistency.
    They help enforce data validation and business rules, preventing the insertion of incorrect or inconsistent data.
                                                                    2
    1.3.6    Default Constraint
    A default constraint specifies a default value for a column if no value is provided during insertion.
1   CREATE TABLE Tasks (
2       TaskID INT PRIMARY KEY ,
3       TaskName VARCHAR (100) ,
4       Status VARCHAR (20) DEFAULT ’ Pending ’
5   );
       SQL constraints play a vital role in maintaining the quality and integrity of your database, ensuring that the data follows
    specific rules and relationships, which is crucial for database consistency and reliability.
    2       SQL Features
    Here are some of the key features of SQL:
        1. Data Retrieval: SQL provides a rich set of commands for retrieving data from a database. The SELECT statement is
           used to retrieve data from one or more database tables. SQL also provides various clauses like WHERE, GROUP BY,
           HAVING, and ORDER BY to refine the data returned by a query.
        2. Data Manipulation: SQL provides commands for modifying data stored in a database. The INSERT statement is used
           to add new records to a table, the UPDATE statement is used to modify existing records, and the DELETE statement is
           used to remove records from a table.
        3. Database Creation and Modification: SQL provides commands for creating and modifying database objects like
           tables, views, indexes, and constraints. These commands enable developers to define the structure of a database, enforce
           data integrity rules, and optimize performance.
        4. Data Integrity: SQL provides various mechanisms for ensuring data integrity, such as constraints, triggers, and transac-
           tions. Constraints ensure that data entered into a table meets certain criteria, while triggers allow developers to execute
           code automatically in response to specific events. Transactions ensure that multiple database operations are executed as
           a single unit of work, and can be rolled back if any errors occur.
        5. Security: SQL provides robust security features, such as user authentication, authorization, and encryption. These
           features enable developers to control access to data stored in a database and protect sensitive information from unauthorized
           access.
        6. Portability: SQL is a standard language that is supported by most relational database management systems (RDBMS).
           This means that SQL code written for one database system can be easily ported to another database system without major
           modifications.
        7. Scalability: SQL is designed to handle large amounts of data and to scale horizontally as the amount of data grows. SQL
           databases can be distributed across multiple servers and can be scaled up or down as needed to meet the demands of an
           application.
        8. Performance: SQL is designed to optimize database performance by providing mechanisms for indexing, query optimiza-
           tion, and database tuning. These features enable developers to ensure that queries execute quickly and efficiently, even
           when working with large data sets.
                                                                     3
3       Data Definition Commands
Data Definition Language (DDL) commands in SQL are used to define and manage the structure of databases and database
objects such as tables, views, indexes, and constraints. DDL commands are used to create, modify, or drop database objects. In
this answer, we will discuss the syntax and purpose of various DDL commands.
    1. CREATE: The CREATE command is used to create new database objects such as tables, views, indexes, and procedures.
       The syntax for the CREATE command is as follows:
    1   CREATE object_type object_name (
    2       column1 datatype1 [ nullable ] ,
    3       column2 datatype2 [ nullable ] , ... ,
    4       columnN datatypeN [ nullable ]
    5   );
          • object type is the type of object being created (e.g. TABLE, VIEW, INDEX, PROCEDURE).
          • object name is the name of the object being created.
          • column1 through columnN are the names of the columns being created in a table or view.
          • datatype1 through datatypeN are the data types for each column.
          • nullable is an optional keyword that specifies whether a column allows null values or not.
        Example:
    1   CREATE TABLE Customers (
    2       customer_id INT NOT NULL ,
    3       first_name VARCHAR (50) ,
    4       last_name VARCHAR (50) NOT NULL ,
    5       email VARCHAR (100) UNIQUE ,
    6       created_date DATE DEFAULT SYSDATE ,
    7       PRIMARY KEY ( customer_id )
    8   );
    2. ALTER: The ALTER command is used to modify the structure of existing database objects such as tables, views, and
       indexes. The syntax for the ALTER command is as follows:
    1   ALTER object_type object_name action ;
          • object type is the type of object being altered (e.g. TABLE, VIEW, INDEX).
          • object name is the name of the object being altered.
          • action is the modification being made to the object (e.g. ADD COLUMN, DROP COLUMN, MODIFY COLUMN).
        Example:
    1   ALTER TABLE Customers ADD COLUMN phone_number VARCHAR (20) ;
    3. DROP: The DROP command is used to delete existing database objects such as tables, views, indexes, and procedures.
       The syntax for the DROP command is as follows:
    1   DROP object_type object_name ;
          • object type is the type of object being dropped (e.g. TABLE, VIEW, INDEX, PROCEDURE).
          • object name is the name of the object being dropped.
        Example:
    1   DROP TABLE Customers ;
    4. TRUNCATE: The TRUNCATE command is used to delete all data from a table. The syntax for the TRUNCATE command
       is as follows:
                                                               4
    1     TRUNCATE TABLE table_name ;
          Example:
    1     TRUNCATE TABLE Customers ;
    5. COMMENT: The COMMENT command is used to add comments to tables, columns, and other database objects. The
       syntax for the COMMENT command is as follows:
    1     COMMENT ON object_type object_name IS ’ comment_text ’;
            • object type is the type of object being commented on (e.g. TABLE, COLUMN).
            • object name is the name of the object being commented on.
            • comment text is the text of the comment.
          Example:
    1     COMMENT ON TABLE Customers IS ’ This table contains information about customers . ’;
    6. INDEX: The INDEX command is used to create an index on one or more columns of a table, which helps to improve query
       performance. The syntax for the INDEX command is as follows:
    1     CREATE [ UNIQUE ] INDEX index_name ON table_name ( column1 [ , column2 , ...]) ;
          The SELECT statement begins with the keyword SELECT, followed by a list of columns to retrieve data from. The column
          names are separated by commas. The FROM keyword is used to specify the table or tables to retrieve data from. The
          WHERE keyword is used to specify one or more conditions to filter the data.
        • INSERT: The INSERT statement is used to insert data into a table in a database. The syntax for INSERT is as follows:
    1     INSERT INTO table_name ( column1 , column2 , ...) VALUES ( value1 , value2 , ...) ;
          The INSERT statement begins with the keyword INSERT INTO, followed by the name of the table to insert data into.
          The column names are enclosed in parentheses and separated by commas. The VALUES keyword is used to specify the
          values to insert into the columns. The values are also enclosed in parentheses and separated by commas.
        • UPDATE: The UPDATE statement is used to update data in a table in a database. The syntax for UPDATE is as
          follows:
    1     UPDATE table_name SET column1 = value1 , column2 = value2 , ... WHERE condition ;
          The UPDATE statement begins with the keyword UPDATE, followed by the name of the table to update data in. The
          SET keyword is used to specify the columns to update and their new values. The column names are followed by an equal
          sign and the new value to set. The WHERE keyword is used to specify one or more conditions to filter the data to be
          updated.
                                                                5
        • DELETE: The DELETE statement is used to delete data from a table in a database. The syntax for DELETE is as
          follows:
    1     DELETE FROM table_name WHERE condition ;
          The DELETE statement begins with the keyword DELETE FROM, followed by the name of the table to delete data from.
          The WHERE keyword is used to specify one or more conditions to filter the data to be deleted.
        • TRUNCATE: The TRUNCATE statement is used to remove all data from a table in a database. The syntax for
          TRUNCATE is as follows:
    1     TRUNCATE TABLE table_name ;
          The TRUNCATE statement begins with the keyword TRUNCATE TABLE, followed by the name of the table to remove
          all data from.
In summary, the syntax for data manipulation commands in SQL can be broken down into several segments, including the
keyword (e.g. SELECT, INSERT, UPDATE), the table name, the column names, the values to insert or update, and the
conditions to filter the data. Understanding these segments is critical to effectively manipulating data in a SQL database.
5        SQL Operators
SQL operators are symbols or keywords used to perform different operations on data stored in a relational database. These
operators are used in SQL queries to retrieve, manipulate, and manage data in tables. SQL operators can be categorized into
several types based on their functionality, including:
    1. Arithmetic Operators: Arithmetic operators in SQL are used to perform various mathematical operations on different
       numeric values, such as calculating totals, averages, and percentages. They can also be used in conjunction with other
       operators and functions to perform more complex calculations. These operators have the Syntax: operand1 operator
       operand2
       These operators include:
            • Addition (+): Adds two values together. Syntax: operand1 + operand2.
              For example, to add two values together: SELECT 5 + 7;
              This will return the value 12.
            • Subtraction (−): Subtracts one value from another. Syntax: operand1 - operand2
            • Multiplication (∗): Multiplies two values together. Syntax: operand1 * operand2
            • Division (/): Divides one value by another. Syntax: operand1 / operand2
            • Modulo (%): Returns the remainder of a division operation.
    2. Comparison Operators: Comparison operators in SQL are used to compare two values and return a boolean result of
       either TRUE or FALSE.
       Syntax: operand1 operator operand2
       These operators include:
            • Equal to (=): Checks whether two values are equal.
            • Not equal to (!= or <>): Checks whether two values are not equal.
            • Greater than (> or >=): Checks whether one value is greater than the other.
            • Less than (< or <=): Checks whether one value is less than the other.
          For example, to compare two values:
    1     SELECT * FROM employees WHERE salary > 50000;
          This will return all employees whose salary is greater than 50000.
    3. Logical Operators: Logical operators are used to combine two or more conditions in SQL. Syntax: condition1 operator
       condition2. These operators include:
            • AND: Returns true if both conditions are true.
            • OR: Returns true if either of the conditions is true.
                                                                      6
                • NOT: Reverses the logical value of the condition.
              For example, to use the AND operator:
        1     SELECT * FROM employees WHERE salary > 50000 AND department = ’ IT ’;
              This will return all employees whose salary is greater than 50000 and who work in the IT department.
        4. Assignment Operators: Assignment operators are used to assign values to variables in SQL. Syntax: variable
           operator value. These operators include:
                • =: Assigns a value to a variable.
                • +=: Adds a value to a variable.
                • -=: Subtracts a value from a variable.
                • *=: Multiplies a variable by a value.
                • /=: Divides a variable by a value.
              For example, to assign a value to a variable:
        1     SET @myVar = ’ Hello , world ! ’;
              This will assign the value ’Hello, world!’ to the variable @myVar.
        5. Concatenation Operator: The concatenation operator is used to combine two or more strings in SQL.
           Syntax: string1 || string2
                • ||: Concatenates two or more strings.
              For example, to concatenate two strings:
        1     SELECT ’ Hello , ’ || ’ world ! ’;
    6         Update Statements
    In SQL, UPDATE statements are used to modify data in a table. They allow you to change one or more values in one or more
    rows of a table based on specified conditions. The syntax for an UPDATE statement is as follows:
1   UPDATE table_name
2   SET column1 = value1 , column2 = value2 , ...
3   WHERE condition ;
This will increase the salary of all employees in the marketing department by 10%.
                                                                       7
    7     Views in SQL
    Views in SQL are virtual tables that are based on the result of a SELECT statement. They do not store any data themselves
    but provide a way to simplify complex queries or to provide controlled access to certain data. The syntax for creating a view is
    as follows:
1   CREATE VIEW view_name AS
2   SELECT column1 , column2 , ...
3   FROM table_name
4   WHERE condition ;
    For example, let’s say we have a table named orders with columns order id, customer id, order date, and total amount.
    We can create a view that shows only the orders that were placed in the last month using the following CREATE VIEW
    statement:
1   CREATE VIEW la st_mon th_ord ers AS
2   SELECT *
3   FROM orders
4   WHERE order_date >= DATEADD ( month , -1 , GETDATE () ) ;
    This view will only show the orders that were placed in the last month, making it easier to analyze recent data without having
    to filter the table every time we run a query.
    This query retrieves all the customers from the ”customers” table where the city is ”New York”.
       Now let’s see an example of a subquery:
1   SELECT * FROM orders WHERE customer_id IN ( SELECT customer_id FROM customers WHERE city
       = ’ New York ’) ;
    This query retrieves all the orders from the ”orders” table where the customer’s city is ”New York”. The subquery is used to
    retrieve the customer IDs of all the customers in New York, which is then used in the main query to retrieve the orders made
    by those customers.
        Subqueries can be used in different parts of a SQL statement, such as in the SELECT, FROM, WHERE, and HAVING
    clauses. They can also be nested to several levels to retrieve more complex data.
                                                                    8
    9.1   Tuple-Oriented Calculus (TRC):
       • TRC is a formal notation that focuses on specifying the conditions that desired tuples or rows in a relational database
         must satisfy.
       • It is part of the broader relational algebra and calculus framework used to query relational databases.
       • TRC abstracts away from the specifics of how data is retrieved and instead emphasizes what data should be retrieved.
       • TRC queries are expressed using a notation that emphasizes the selection criteria for tuples (rows) in a table.
       • TRC is not commonly used in practice as a query language but is more of a theoretical concept used for database query
         language research and understanding.
    In this TRC query, we are expressing the condition that we want tuples from the ”employees” table where the salary is greater
    than $50,000. It emphasizes the ”what” (the selection criteria) rather than the ”how” (the steps to retrieve the data).
       • DRC, however, focuses on specifying conditions on individual attributes or domains (columns) rather than on tuples.
       • It allows for expressing queries in terms of what should be retrieved based on conditions applied to specific attributes.
       • DRC is also not commonly used in practical SQL implementations but is used in database theory and research.
    In this DRC query, we are specifying that we want the first names of employees whose salary exceeds $50,000. DRC lets us
    express conditions on specific attributes, providing a more granular level of control over query criteria.
       In summary, TRC and DRC are theoretical concepts used to describe different approaches to formulating queries in relational
    databases. While they emphasize the declarative nature of queries and what data should be retrieved, they are not practical
    query languages used in everyday SQL database operations. SQL itself is the dominant query language for relational databases
    and is used to specify both ”what” data should be retrieved and ”how” it should be retrieved.