Category: sqlite

  • Khóa học miễn phí SQLite – Transactions nhận dự án làm có lương

    SQLite – Transactions



    A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.

    A transaction is the propagation of one or more changes to the database. For example, if you are creating, updating, or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors.

    Practically, you will club many SQLite queries into a group and you will execute all of them together as part of a transaction.

    Properties of Transactions

    Transactions have the following four standard properties, usually referred to by the acronym ACID.

    • Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state.

    • Consistency − Ensures that the database properly changes states upon a successfully committed transaction.

    • Isolation − Enables transactions to operate independently of and transparent to each other.

    • Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure.

    Transaction Control

    Following are the following commands used to control transactions:

    • BEGIN TRANSACTION − To start a transaction.

    • COMMIT − To save the changes, alternatively you can use END TRANSACTION command.

    • ROLLBACK − To rollback the changes.

    Transactional control commands are only used with DML commands INSERT, UPDATE, and DELETE. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database.

    BEGIN TRANSACTION Command

    Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command is encountered. However, a transaction will also ROLLBACK if the database is closed or if an error occurs. Following is the simple syntax to start a transaction.

    BEGIN;
    or
    BEGIN TRANSACTION;
    

    COMMIT Command

    COMMIT command is the transactional command used to save changes invoked by a transaction to the database.

    COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command.

    Following is the syntax for COMMIT command.

    COMMIT;
    or
    END TRANSACTION;
    

    ROLLBACK Command

    ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database.

    ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.

    Following is the syntax for ROLLBACK command.

    ROLLBACK;
    

    Example

    Consider table with the following records.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Now, let”s start a transaction and delete records from the table having age = 25. Then, use ROLLBACK command to undo all the changes.

    sqlite> BEGIN;
    sqlite> DELETE FROM COMPANY WHERE AGE = 25;
    sqlite> ROLLBACK;
    

    Now, if you check COMPANY table, it still has the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Let”s start another transaction and delete records from the table having age = 25 and finally we use COMMIT command to commit all the changes.

    sqlite> BEGIN;
    sqlite> DELETE FROM COMPANY WHERE AGE = 25;
    sqlite> COMMIT;
    

    If you now check COMPANY table is still has the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    3           Teddy       23          Norway      20000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – Injection nhận dự án làm có lương

    SQLite – Injection



    If you take user input through a webpage and insert it into a SQLite database there”s a chance that you have left yourself wide open for a security issue known as SQL Injection. In this chapter, you will learn how to help prevent this from happening and help you secure your scripts and SQLite statements.

    Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a SQLite statement that you will unknowingly run on your database.

    Never trust user provided data, process this data only after validation; as a rule, this is done by pattern matching. In the following example, the username is restricted to alphanumerical chars plus underscore and to a length between 8 and 20 chars – modify these rules as needed.

    if (preg_match("/^w{8,20}$/", $_GET[''username''], $matches)){
       $db = new SQLiteDatabase(''filename'');
       $result = @$db->query("SELECT * FROM users WHERE username = $matches[0]");
    } else {
       echo "username not accepted";
    }
    

    To demonstrate the problem, consider this excerpt −

    $name = "Qadir DELETE FROM users;";
    @$db->query("SELECT * FROM users WHERE username = ''{$name}''");
    

    The function call is supposed to retrieve a record from the users table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces, such as the string ilia. However in this case, by appending an entirely new query to $name, the call to the database turns into a disaster: the injected DELETE query removes all records from users.

    There are databases interfaces which do not permit query stacking or executing multiple queries in a single function call. If you try to stack queries, the call fails but SQLite and PostgreSQL, happily perform stacked queries, executing all of the queries provided in one string and creating a serious security problem.

    Preventing SQL Injection

    You can handle all escape characters smartly in scripting languages like PERL and PHP. Programming language PHP provides the function string sqlite_escape_string() to escape input characters that are special to SQLite.

    if (get_magic_quotes_gpc()) {
       $name = sqlite_escape_string($name);
    }
    $result = @$db->query("SELECT * FROM users WHERE username = ''{$name}''");
    

    Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data.

    Noteaddslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – EXPLAIN nhận dự án làm có lương

    SQLite – EXPLAIN



    SQLite statement can be preceded by the keyword “EXPLAIN” or by the phrase “EXPLAIN QUERY PLAN” used for describing the details of a table.

    Either modification causes the SQLite statement to behave as a query and to return information about how the SQLite statement would have operated if the EXPLAIN keyword or phrase had been omitted.

    • The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for interactive analysis and troubleshooting only.

    • The details of the output format are subject to change from one release of SQLite to the next.

    • Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since their exact behavior is variable and only partially documented.

    Syntax

    syntax for EXPLAIN is as follows −

    EXPLAIN [SQLite Query]
    

    syntax for EXPLAIN QUERY PLAN is as follows −

    EXPLAIN  QUERY PLAN [SQLite Query]
    

    Example

    Consider table with the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Now, let us check the following sub-query with SELECT statement −

    sqlite> EXPLAIN SELECT * FROM COMPANY WHERE Salary &gt= 20000;
    

    This will produce the following result.

    addr        opcode      p1          p2          p3
    ----------  ----------  ----------  ----------  ----------
    0           Goto        0           19
    1           Integer     0           0
    2           OpenRead    0           8
    3           SetNumColu  0           5
    4           Rewind      0           17
    5           Column      0           4
    6           RealAffini  0           0
    7           Integer     20000       0
    8           Lt          357         16          collseq(BI
    9           Rowid       0           0
    10          Column      0           1
    11          Column      0           2
    12          Column      0           3
    13          Column      0           4
    14          RealAffini  0           0
    15          Callback    5           0
    16          Next        0           5
    17          Close       0           0
    18          Halt        0           0
    19          Transactio  0           0
    20          VerifyCook  0           38
    21          Goto        0           1
    22          Noop        0           0
    

    Now, let us check the following Explain Query Plan with SELECT statement −

    SQLite> EXPLAIN QUERY PLAN SELECT * FROM COMPANY WHERE Salary &gt= 20000;
    
    order       from        detail
    ----------  ----------  -------------
    0           0           TABLE COMPANY
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – AUTOINCREMENT nhận dự án làm có lương

    SQLite – AUTOINCREMENT



    SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment.

    The keyword AUTOINCREMENT can be used with INTEGER field only.

    Syntax

    The basic usage of AUTOINCREMENT keyword is as follows −

    CREATE TABLE table_name(
       column1 INTEGER AUTOINCREMENT,
       column2 datatype,
       column3 datatype,
       .....
       columnN datatype,
    );
    

    Example

    Consider COMPANY table to be created as follows −

    sqlite> CREATE TABLE COMPANY(
       ID INTEGER PRIMARY KEY AUTOINCREMENT,
       NAME           TEXT      NOT NULL,
       AGE            INT       NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL
    );
    

    Now, insert the following records into table COMPANY −

    INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
    VALUES ( ''Paul'', 32, ''California'', 20000.00 );
    
    INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
    VALUES (''Allen'', 25, ''Texas'', 15000.00 );
    
    INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
    VALUES (''Teddy'', 23, ''Norway'', 20000.00 );
    
    INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
    VALUES ( ''Mark'', 25, ''Rich-Mond '', 65000.00 );
    
    INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
    VALUES ( ''David'', 27, ''Texas'', 85000.00 );
    
    INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
    VALUES ( ''Kim'', 22, ''South-Hall'', 45000.00 );
    
    INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
    VALUES ( ''James'', 24, ''Houston'', 10000.00 );
    

    This will insert 7 tuples into the table COMPANY and COMPANY will have the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – Subqueries nhận dự án làm có lương

    SQLite – Subqueries



    A Subquery or Inner query or Nested query is a query within another SQLite query and embedded within the WHERE clause.

    A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.

    Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators such as =, <, >, >=, <=, IN, BETWEEN, etc.

    There are a few rules that subqueries must follow −

    • Subqueries must be enclosed within parentheses.

    • A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.

    • An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.

    • Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.

    • BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery.

    Subqueries with SELECT Statement

    Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −

    SELECT column_name [, column_name ]
    FROM table1 [, table2 ]
    WHERE column_name OPERATOR
       (SELECT column_name [, column_name ]
          FROM table1 [, table2 ]
          [WHERE])
    

    Example

    Consider table with the following records.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Now, let us check the following sub-query with SELECT statement.

    sqlite> SELECT *
       FROM COMPANY
       WHERE ID IN (SELECT ID
          FROM COMPANY
          WHERE SALARY > 45000) ;
    

    This will produce the following result.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    

    Subqueries with INSERT Statement

    Subqueries can also be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions.

    Following is the basic syntax is as follows −

    INSERT INTO table_name [ (column1 [, column2 ]) ]
       SELECT [ *|column1 [, column2 ]
       FROM table1 [, table2 ]
       [ WHERE VALUE OPERATOR ]
    

    Example

    Consider a table COMPANY_BKP with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. To copy the complete COMPANY table into COMPANY_BKP, following is the syntax −

    sqlite> INSERT INTO COMPANY_BKP
       SELECT * FROM COMPANY
       WHERE ID IN (SELECT ID
          FROM COMPANY) ;
    

    Subqueries with UPDATE Statement

    The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.

    Following is the basic syntax is as follows −

    UPDATE table
    SET column_name = new_value
    [ WHERE OPERATOR [ VALUE ]
       (SELECT COLUMN_NAME
          FROM TABLE_NAME)
       [ WHERE) ]
    

    Example

    Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table.

    Following example updates SALARY by 0.50 times in COMPANY table for all the customers, whose AGE is greater than or equal to 27.

    sqlite> UPDATE COMPANY
       SET SALARY = SALARY * 0.50
       WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
          WHERE AGE >= 27 );
    

    This would impact two rows and finally COMPANY table would have the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  10000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       42500.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Subqueries with DELETE Statement

    Subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.

    Following is the basic syntax is as follows −

    DELETE FROM TABLE_NAME
    [ WHERE OPERATOR [ VALUE ]
       (SELECT COLUMN_NAME
          FROM TABLE_NAME)
       [ WHERE) ]
    

    Example

    Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table.

    Following example deletes records from COMPANY table for all the customers whose AGE is greater than or equal to 27.

    sqlite> DELETE FROM COMPANY
       WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
       WHERE AGE > 27 );
    

    This will impact two rows and finally COMPANY table will have the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       42500.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – JOINS nhận dự án làm có lương

    SQLite – JOINS



    SQLite Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.

    SQL defines three major types of joins −

    • The CROSS JOIN
    • The INNER JOIN
    • The OUTER JOIN

    Before we proceed, let”s consider two tables COMPANY and DEPARTMENT. We already have seen INSERT statements to populate COMPANY table. So just let”s assume the list of records available in COMPANY table −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Another table is DEPARTMENT with the following definition −

    CREATE TABLE DEPARTMENT(
       ID INT PRIMARY KEY      NOT NULL,
       DEPT           CHAR(50) NOT NULL,
       EMP_ID         INT      NOT NULL
    );
    

    Here is the list of INSERT statements to populate DEPARTMENT table −

    INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)
    VALUES (1, ''IT Billing'', 1 );
    
    INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)
    VALUES (2, ''Engineering'', 2 );
    
    INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)
    VALUES (3, ''Finance'', 7 );
    

    Finally, we have the following list of records available in DEPARTMENT table −

    ID          DEPT        EMP_ID
    ----------  ----------  ----------
    1           IT Billing  1
    2           Engineering 2
    3           Finance     7
    

    The CROSS JOIN

    CROSS JOIN matches every row of the first table with every row of the second table. If the input tables have x and y row, respectively, the resulting table will have x*y row. Because CROSS JOINs have the potential to generate extremely large tables, care must be taken to only use them when appropriate.

    Following is the syntax of CROSS JOIN −

    SELECT ... FROM table1 CROSS JOIN table2 ...
    

    Based on the above tables, you can write a CROSS JOIN as follows −

    sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT;
    

    The above query will produce the following result −

    EMP_ID      NAME        DEPT
    ----------  ----------  ----------
    1           Paul        IT Billing
    2           Paul        Engineering
    7           Paul        Finance
    1           Allen       IT Billing
    2           Allen       Engineering
    7           Allen       Finance
    1           Teddy       IT Billing
    2           Teddy       Engineering
    7           Teddy       Finance
    1           Mark        IT Billing
    2           Mark        Engineering
    7           Mark        Finance
    1           David       IT Billing
    2           David       Engineering
    7           David       Finance
    1           Kim         IT Billing
    2           Kim         Engineering
    7           Kim         Finance
    1           James       IT Billing
    2           James       Engineering
    7           James       Finance
    

    The INNER JOIN

    INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows of A and B are combined into a result row.

    An INNER JOIN is the most common and default type of join. You can use INNER keyword optionally.

    Following is the syntax of INNER JOIN −

    SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression ...
    

    To avoid redundancy and keep the phrasing shorter, INNER JOIN conditions can be declared with a USING expression. This expression specifies a list of one or more columns.

    SELECT ... FROM table1 JOIN table2 USING ( column1 ,... ) ...
    

    A NATURAL JOIN is similar to a JOIN…USING, only it automatically tests for equality between the values of every column that exists in both tables −

    SELECT ... FROM table1 NATURAL JOIN table2...
    

    Based on the above tables, you can write an INNER JOIN as follows −

    sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
       ON COMPANY.ID = DEPARTMENT.EMP_ID;
    

    The above query will produce the following result −

    EMP_ID      NAME        DEPT
    ----------  ----------  ----------
    1           Paul        IT Billing
    2           Allen       Engineering
    7           James       Finance
    

    The OUTER JOIN

    OUTER JOIN is an extension of INNER JOIN. Though SQL standard defines three types of OUTER JOINs: LEFT, RIGHT, and FULL, SQLite only supports the LEFT OUTER JOIN.

    OUTER JOINs have a condition that is identical to INNER JOINs, expressed using an ON, USING, or NATURAL keyword. The initial results table is calculated the same way. Once the primary JOIN is calculated, an OUTER JOIN will take any unjoined rows from one or both tables, pad them out with NULLs, and append them to the resulting table.

    Following is the syntax of LEFT OUTER JOIN −

    SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ...
    

    To avoid redundancy and keep the phrasing shorter, OUTER JOIN conditions can be declared with a USING expression. This expression specifies a list of one or more columns.

    SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( column1 ,... ) ...
    

    Based on the above tables, you can write an outer join as follows −

    sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
       ON COMPANY.ID = DEPARTMENT.EMP_ID;
    

    The above query will produce the following result −

    EMP_ID      NAME        DEPT
    ----------  ----------  ----------
    1           Paul        IT Billing
    2           Allen       Engineering
                Teddy
                Mark
                David
                Kim
    7           James       Finance
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – UNIONS Clause nhận dự án làm có lương

    SQLite – UNION Clause



    SQLite UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.

    To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be of the same length.

    Syntax

    Following is the basic syntax of UNION.

    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    
    UNION
    
    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    

    Here the given condition could be any given expression based on your requirement.

    Example

    Consider the following two tables, (a) table as follows −

    sqlite> select * from COMPANY;
    ID          NAME                  AGE         ADDRESS     SALARY
    ----------  --------------------  ----------  ----------  ----------
    1           Paul                  32          California  20000.0
    2           Allen                 25          Texas       15000.0
    3           Teddy                 23          Norway      20000.0
    4           Mark                  25          Rich-Mond   65000.0
    5           David                 27          Texas       85000.0
    6           Kim                   22          South-Hall  45000.0
    7           James                 24          Houston     10000.0
    

    (b) Another table is as follows −

    ID          DEPT                  EMP_ID
    ----------  --------------------  ----------
    1           IT Billing            1
    2           Engineering           2
    3           Finance               7
    4           Engineering           3
    5           Finance               4
    6           Engineering           5
    7           Finance               6
    

    Now let us join these two tables using SELECT statement along with UNION clause as follows −

    sqlite>  SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
             ON COMPANY.ID = DEPARTMENT.EMP_ID
    
             UNION
    
             SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
             ON COMPANY.ID = DEPARTMENT.EMP_ID;
    

    This will produce the following result.

    EMP_ID      NAME                  DEPT
    ----------  --------------------  ----------
    1           Paul                  IT Billing
    2           Allen                 Engineering
    3           Teddy                 Engineering
    4           Mark                  Finance
    5           David                 Engineering
    6           Kim                   Finance
    7           James                 Finance
    

    The UNION ALL Clause

    The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows.

    The same rules that apply to UNION apply to the UNION ALL operator as well.

    Syntax

    Following is the basic syntax of UNION ALL.

    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    
    UNION ALL
    
    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    

    Here the given condition could be any given expression based on your requirement.

    Example

    Now, let us join the above-mentioned two tables in our SELECT statement as follows −

    sqlite>  SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
             ON COMPANY.ID = DEPARTMENT.EMP_ID
    
             UNION ALL
    
             SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
             ON COMPANY.ID = DEPARTMENT.EMP_ID;
    

    This will produce the following result.

    EMP_ID      NAME                  DEPT
    ----------  --------------------  ----------
    1           Paul                  IT Billing
    2           Allen                 Engineering
    3           Teddy                 Engineering
    4           Mark                  Finance
    5           David                 Engineering
    6           Kim                   Finance
    7           James                 Finance
    1           Paul                  IT Billing
    2           Allen                 Engineering
    3           Teddy                 Engineering
    4           Mark                  Finance
    5           David                 Engineering
    6           Kim                   Finance
    7           James                 Finance
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – WHERE Clause nhận dự án làm có lương

    SQLite – WHERE Clause



    SQLite WHERE clause is used to specify a condition while fetching the data from one table or multiple tables.

    If the given condition is satisfied, means true, then it returns the specific value from the table. You will have to use WHERE clause to filter the records and fetching only necessary records.

    The WHERE clause not only is used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which will be covered in subsequent chapters.

    Syntax

    Following is the basic syntax of SQLite SELECT statement with WHERE clause.

    SELECT column1, column2, columnN
    FROM table_name
    WHERE [condition]
    

    Example

    You can specify a condition using such as >, <, =, LIKE, NOT, etc. Consider COMPANY table with the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following is a simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00.

    sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    

    Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00.

    sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    

    Following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record has AGE equal to NULL.

    sqlite>  SELECT * FROM COMPANY WHERE AGE IS NOT NULL;
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following SELECT statement lists down all the records where NAME starts with ”Ki”, does not matter what comes after ”Ki”.

    sqlite> SELECT * FROM COMPANY WHERE NAME LIKE ''Ki%
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    6           Kim         22          South-Hall  45000.0
    

    Following SELECT statement lists down all the records where NAME starts with ”Ki”, does not matter what comes after ”Ki”.

    sqlite> SELECT * FROM COMPANY WHERE NAME GLOB ''Ki*
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    6           Kim         22          South-Hall  45000.0
    

    Following SELECT statement lists down all the records where AGE value is either 25 or 27.

    sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    2           Allen       25          Texas       15000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    

    Following SELECT statement lists down all the records where AGE value is neither 25 nor 27.

    sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    3           Teddy       23          Norway      20000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27.

    sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    2           Allen       25          Texas       15000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    

    Following SELECT statement makes use of SQL sub-query, where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query −

    sqlite> SELECT AGE FROM COMPANY
       WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
    
    AGE
    ----------
    32
    25
    23
    25
    27
    22
    24
    

    Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query.

    sqlite> SELECT * FROM COMPANY
       WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – DELETE Query nhận dự án làm có lương

    SQLite – DELETE Query



    SQLite DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows, otherwise all the records would be deleted.

    Syntax

    Following is the basic syntax of DELETE query with WHERE clause.

    DELETE FROM table_name
    WHERE [condition];
    

    You can combine N number of conditions using AND or OR operators.

    Example

    Consider COMPANY table with the following records.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following is an example, which will DELETE a customer whose ID is 7.

    sqlite> DELETE FROM COMPANY WHERE ID = 7;
    

    Now COMPANY table will have the following records.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    

    If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE query, which will be as follows −

    sqlite> DELETE FROM COMPANY;
    

    Now, COMPANY table does not have any record as all the records have been deleted by DELETE statement.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQLite – AND & OR Clauses nhận dự án làm có lương

    SQLite – AND & OR Operators



    SQLite AND & OR operators are used to compile multiple conditions to narrow down the selected data in an SQLite statement. These two operators are called conjunctive operators.

    These operators provide a means to make multiple comparisons with different operators in the same SQLite statement.

    The AND Operator

    The AND operator allows the existence of multiple conditions in a SQLite statement”s WHERE clause. While using AND operator, complete condition will be assumed true when all the conditions are true. For example, [condition1] AND [condition2] will be true only when both condition1 and condition2 are true.

    Syntax

    Following is the basic syntax of AND operator with WHERE clause.

    SELECT column1, column2, columnN
    FROM table_name
    WHERE [condition1] AND [condition2]...AND [conditionN];
    

    You can combine N number of conditions using AND operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE.

    Example

    Consider COMPANY table with the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00.

    sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    

    The OR Operator

    The OR operator is also used to combine multiple conditions in a SQLite statement”s WHERE clause. While using OR operator, complete condition will be assumed true when at least any of the conditions is true. For example, [condition1] OR [condition2] will be true if either condition1 or condition2 is true.

    Syntax

    Following is the basic syntax of OR operator with WHERE clause.

    SELECT column1, column2, columnN
    FROM table_name
    WHERE [condition1] OR [condition2]...OR [conditionN]
    

    You can combine N number of conditions using OR operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE.

    Example

    Consider COMPANY table with the following records.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00.

    sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
    
    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc