Author: alien

  • 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 – Constraints nhận dự án làm có lương

    SQLite – Constraints



    Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database.

    Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table.

    Following are commonly used constraints available in SQLite.

    • NOT NULL Constraint − Ensures that a column cannot have NULL value.

    • DEFAULT Constraint − Provides a default value for a column when none is specified.

    • UNIQUE Constraint − Ensures that all values in a column are different.

    • PRIMARY Key − Uniquely identifies each row/record in a database table.

    • CHECK Constraint − Ensures that all values in a column satisfies certain conditions.

    NOT NULL Constraint

    By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed for that column.

    A NULL is not the same as no data, rather, it represents unknown data.

    Example

    For example, the following SQLite statement creates a new table called COMPANY and adds five columns, three of which, ID and NAME and AGE, specifies not to accept NULLs.

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

    DEFAULT Constraint

    The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value.

    Example

    For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, SALARY column is set to 5000.00 by default, thus in case INSERT INTO statement does not provide a value for this column, then by default, this column would be set to 5000.00.

    CREATE TABLE COMPANY(
       ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL    DEFAULT 50000.00
    );
    

    UNIQUE Constraint

    The UNIQUE Constraint prevents two records from having identical values in a particular column. In the COMPANY table, for example, you might want to prevent two or more people from having an identical age.

    Example

    For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with the same age −

    CREATE TABLE COMPANY(
       ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL UNIQUE,
       ADDRESS        CHAR(50),
       SALARY         REAL    DEFAULT 50000.00
    );
    

    PRIMARY KEY Constraint

    The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the database tables. Primary keys are unique IDs.

    We use them to refer to table rows. Primary keys become foreign keys in other tables, when creating relations among tables. Due to a ”longstanding coding oversight”, primary keys can be NULL in SQLite. This is not the case with other databases.

    A primary key is a field in a table which uniquely identifies each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.

    A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.

    If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).

    Example

    You already have seen various examples above where we have created COMPANY table with ID as a primary key.

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

    CHECK Constraint

    CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn”t entered into the table.

    Example

    For example, the following SQLite creates a new table called COMPANY and adds five columns. Here, we add a CHECK with SALARY column, so that you cannot have any SALARY Zero.

    CREATE TABLE COMPANY3(
       ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL    CHECK(SALARY > 0)
    );
    

    Dropping Constraint

    SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.


    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 – DISTINCT Keyword nhận dự án làm có lương

    SQLite – DISTINCT Keyword



    SQLite DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only the unique records.

    There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.

    Syntax

    Following is the basic syntax of DISTINCT keyword to eliminate duplicate records.

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

    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
    8           Paul        24          Houston     20000.0
    9           James       44          Norway      5000.0
    10          James       45          Texas       5000.0
    

    First, let us see how the following SELECT query returns duplicate salary records.

    sqlite> SELECT name FROM COMPANY;
    

    This will produce the following result.

    NAME
    ----------
    Paul
    Allen
    Teddy
    Mark
    David
    Kim
    James
    Paul
    James
    James
    

    Now, let us use DISTINCT keyword with the above SELECT query and see the result.

    sqlite> SELECT DISTINCT name FROM COMPANY;
    

    This will produce the following result, where there is no duplicate entry.

    NAME
    ----------
    Paul
    Allen
    Teddy
    Mark
    David
    Kim
    James
    

    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 – PRAGMA nhận dự án làm có lương

    SQLite – PRAGMA



    SQLite PRAGMA command is a special command to be used to control various environmental variables and state flags within the SQLite environment. A PRAGMA value can be read and it can also be set based on the requirements.

    Syntax

    To query the current PRAGMA value, just provide the name of the pragma.

    PRAGMA pragma_name;
    

    To set a new value for PRAGMA, use the following syntax.

    PRAGMA pragma_name = value;
    

    The set mode can be either the name or the integer equivalent but the returned value will always be an integer.

    auto_vacuum Pragma

    The auto_vacuum pragma gets or sets the auto-vacuum mode. Following is the simple syntax.

    PRAGMA [database.]auto_vacuum;
    PRAGMA [database.]auto_vacuum = mode;
    

    Where mode can be any of the following −

    Sr.No. Pragma Value & Description
    1

    0 or NONE

    Auto-vacuum is disabled. This is the default mode which means that a database file will never shrink in size unless it is manually vacuumed using the VACUUM command.

    2

    1 or FULL

    Auto-vacuum is enabled and fully automatic which allows a database file to shrink as data is removed from the database.

    3

    2 or INCREMENTAL

    Auto-vacuum is enabled but must be manually activated. In this mode the reference data is maintained, but free pages are simply put on the free list. These pages can be recovered using the incremental_vacuum pragma any time.

    cache_size Pragma

    The cache_size pragma can get or temporarily set the maximum size of the in-memory page cache. Following is the simple syntax.

    PRAGMA [database.]cache_size;
    PRAGMA [database.]cache_size = pages;
    

    The pages value represents the number of pages in the cache. The built-in page cache has a default size of 2,000 pages and a minimum size of 10 pages.

    case_sensitive_like Pragma

    The case_sensitive_like pragma controls the case-sensitivity of the built-in LIKE expression. By default, this pragma is false which means that the built-in LIKE operator ignores the letter case. Following is the simple syntax.

    PRAGMA case_sensitive_like = [true|false];
    

    There is no way to query for the current state of this pragma.

    count_changes Pragma

    count_changes pragma gets or sets the return value of data manipulation statements such as INSERT, UPDATE and DELETE. Following is the simple syntax.

    PRAGMA count_changes;
    PRAGMA count_changes = [true|false];
    

    By default, this pragma is false and these statements do not return anything. If set to true, each of the mentioned statement will return a one-column, one-row table consisting of a single integer value indicating impacted rows by the operation.

    database_list Pragma

    The database_list pragma will be used to list down all the databases attached. Following is the simple syntax.

    PRAGMA database_list;
    

    This pragma will return a three-column table with one row per open or attached database giving database sequence number, its name and the file associated.

    encoding Pragma

    The encoding pragma controls how strings are encoded and stored in a database file. Following is the simple syntax.

    PRAGMA encoding;
    PRAGMA encoding = format;
    

    The format value can be one of UTF-8, UTF-16le, or UTF-16be.

    freelist_count Pragma

    The freelist_count pragma returns a single integer indicating how many database pages are currently marked as free and available. Following is the simple syntax.

    PRAGMA [database.]freelist_count;
    

    The format value can be one of UTF-8, UTF-16le, or UTF-16be.

    index_info Pragma

    The index_info pragma returns information about a database index. Following is the simple syntax.

    PRAGMA [database.]index_info( index_name );
    

    The result set will contain one row for each column contained in the index giving column sequence, column index with-in table and column name.

    index_list Pragma

    index_list pragma lists all of the indexes associated with a table. Following is the simple syntax.

    PRAGMA [database.]index_list( table_name );
    

    The result set will contain one row for each index giving index sequence, index name and flag indicating whether the index is unique or not.

    journal_mode Pragma

    The journal_mode pragma gets or sets the journal mode which controls how the journal file is stored and processed. Following is the simple syntax.

    PRAGMA journal_mode;
    PRAGMA journal_mode = mode;
    PRAGMA database.journal_mode;
    PRAGMA database.journal_mode = mode;
    

    There are five supported journal modes as listed in the following table.

    Sr.No. Pragma Value & Description
    1

    DELETE

    This is the default mode. Here at the conclusion of a transaction, the journal file is deleted.

    2

    TRUNCATE

    The journal file is truncated to a length of zero bytes.

    3

    PERSIST

    The journal file is left in place, but the header is overwritten to indicate the journal is no longer valid.

    4

    MEMORY

    The journal record is held in memory, rather than on disk.

    5

    OFF

    No journal record is kept.

    max_page_count Pragma

    The max_page_count pragma gets or sets the maximum allowed page count for a database. Following is the simple syntax.

    PRAGMA [database.]max_page_count;
    PRAGMA [database.]max_page_count = max_page;
    

    The default value is 1,073,741,823 which is one giga-page, which means if the default 1 KB page size, this allows databases to grow up to one terabyte.

    page_count Pragma

    The page_count pragma returns in the current number of pages in the database. Following is the simple syntax −

    PRAGMA [database.]page_count;
    

    The size of the database file should be page_count * page_size.

    page_size Pragma

    The page_size pragma gets or sets the size of the database pages. Following is the simple syntax.

    PRAGMA [database.]page_size;
    PRAGMA [database.]page_size = bytes;
    

    By default, the allowed sizes are 512, 1024, 2048, 4096, 8192, 16384, and 32768 bytes. The only way to alter the page size on an existing database is to set the page size and then immediately VACUUM the database.

    parser_trace Pragma

    The parser_trace pragma controls printing the debugging state as it parses SQL commands. Following is the simple syntax.

    PRAGMA parser_trace = [true|false];
    

    By default, it is set to false but when enabled by setting it to true, the SQL parser will print its state as it parses SQL commands.

    recursive_triggers Pragma

    The recursive_triggers pragma gets or sets the recursive trigger functionality. If recursive triggers are not enabled, a trigger action will not fire another trigger. Following is the simple syntax.

    PRAGMA recursive_triggers;
    PRAGMA recursive_triggers = [true|false];
    

    schema_version Pragma

    The schema_version pragma gets or sets the schema version value that is stored in the database header. Following is the simple syntax.

    PRAGMA [database.]schema_version;
    PRAGMA [database.]schema_version = number;
    

    This is a 32-bit signed integer value that keeps track of schema changes. Whenever a schema-altering command is executed (like, CREATE… or DROP…), this value is incremented.

    secure_delete Pragma

    The secure_delete pragma is used to control how the content is deleted from the database. Following is the simple syntax.

    PRAGMA secure_delete;
    PRAGMA secure_delete = [true|false];
    PRAGMA database.secure_delete;
    PRAGMA database.secure_delete = [true|false];
    

    The default value for the secure delete flag is normally off, but this can be changed with the SQLITE_SECURE_DELETE build option.

    sql_trace Pragma

    The sql_trace pragma is used to dump SQL trace results to the screen. Following is the simple syntax.

    PRAGMA sql_trace;
    PRAGMA sql_trace = [true|false];
    

    SQLite must be compiled with the SQLITE_DEBUG directive for this pragma to be included.

    synchronous Pragma

    The synchronous pragma gets or sets the current disk synchronization mode, which controls how aggressively SQLite will write data all the way out to physical storage. Following is the simple syntax.

    PRAGMA [database.]synchronous;
    PRAGMA [database.]synchronous = mode;
    

    SQLite supports the following synchronization modes as listed in the table.

    Sr.No. Pragma Value & Description
    1

    0 or OFF

    No syncs at all

    2

    1 or NORMAL

    Sync after each sequence of critical disk operations

    3

    2 or FULL

    Sync after each critical disk operation

    temp_store Pragma

    The temp_store pragma gets or sets the storage mode used by temporary database files. Following is the simple syntax.

    PRAGMA temp_store;
    PRAGMA temp_store = mode;
    

    SQLite supports the following storage modes.

    Sr.No. Pragma Value & Description
    1

    0 or DEFAULT

    Use compile-time default. Normally FILE.

    2

    1 or FILE

    Use file-based storage.

    3

    2 or MEMORY

    Use memory-based storage.

    temp_store_directory Pragma

    The temp_store_directory pragma gets or sets the location used for temporary database files. Following is the simple syntax.

    PRAGMA temp_store_directory;
    PRAGMA temp_store_directory = ''directory_path
    

    user_version Pragma

    The user_version pragma gets or sets the user-defined version value that is stored in the database header. Following is the simple syntax.

    PRAGMA [database.]user_version;
    PRAGMA [database.]user_version = number;
    

    This is a 32-bit signed integer value, which can be set by the developer for version tracking purpose.

    writable_schema Pragma

    The writable_schema pragma gets or sets the ability to modify system tables. Following is the simple syntax.

    PRAGMA writable_schema;
    PRAGMA writable_schema = [true|false];
    

    If this pragma is set, tables that start with sqlite_ can be created and modified, including the sqlite_master table. Be careful while using pragma because it can lead to complete database corruption.


    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 – ORDER By Clause nhận dự án làm có lương

    SQLite – ORDER BY Clause



    SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns.

    Syntax

    Following is the basic syntax of ORDER BY clause.

    SELECT column-list
    FROM table_name
    [WHERE condition]
    [ORDER BY column1, column2, .. columnN] [ASC | DESC];
    

    You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be available in the column-list.

    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 sort the result in descending order by SALARY.

    sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC;
    

    This will produce the following result.

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

    Following is an example, which will sort the result in descending order by NAME and SALARY.

    sqlite> SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
    

    This will produce the following result.

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

    Following is an example, which will sort the result in descending order by NAME.

    sqlite> SELECT * FROM COMPANY ORDER BY NAME DESC;
    

    This will produce the following result.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    3           Teddy       23          Norway      20000.0
    1           Paul        32          California  20000.0
    4           Mark        25          Rich-Mond   65000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    5           David       27          Texas       85000.0
    2           Allen       25          Texas       15000.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 – GROUP By Clause nhận dự án làm có lương

    SQLite – GROUP BY Clause



    SQLite GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.

    GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

    Syntax

    Following is the basic syntax of GROUP BY clause. GROUP BY clause must follow the conditions in the WHERE clause and must precede ORDER BY clause if one is used.

    SELECT column-list
    FROM table_name
    WHERE [ conditions ]
    GROUP BY column1, column2....columnN
    ORDER BY column1, column2....columnN
    

    You can use more than one column in the GROUP BY clause. Make sure whatever column you are using to group, that column should be available in the column-list.

    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
    

    If you want to know the total amount of salary on each customer, then GROUP BY query will be as follows −

    sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;
    

    This will produce the following result −

    NAME        SUM(SALARY)
    ----------  -----------
    Allen       15000.0
    David       85000.0
    James       10000.0
    Kim         45000.0
    Mark        65000.0
    Paul        20000.0
    Teddy       20000.0
    

    Now, let us create three more records in COMPANY table using the following INSERT statements.

    INSERT INTO COMPANY VALUES (8, ''Paul'', 24, ''Houston'', 20000.00 );
    INSERT INTO COMPANY VALUES (9, ''James'', 44, ''Norway'', 5000.00 );
    INSERT INTO COMPANY VALUES (10, ''James'', 45, ''Texas'', 5000.00 );
    

    Now, our table has the following records with duplicate names.

    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
    8           Paul        24          Houston     20000.0
    9           James       44          Norway      5000.0
    10          James       45          Texas       5000.0
    

    Again, let us use the same statement to group-by all the records using NAME column as follows −

    sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;
    

    This will produce the following result.

    NAME        SUM(SALARY)
    ----------  -----------
    Allen       15000
    David       85000
    James       20000
    Kim         45000
    Mark        65000
    Paul        40000
    Teddy       20000
    

    Let us use ORDER BY clause along with GROUP BY clause as follows −

    sqlite>  SELECT NAME, SUM(SALARY)
       FROM COMPANY GROUP BY NAME ORDER BY NAME DESC;
    

    This will produce the following result.

    NAME        SUM(SALARY)
    ----------  -----------
    Teddy       20000
    Paul        40000
    Mark        65000
    Kim         45000
    James       20000
    David       85000
    Allen       15000
    

    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 – LIMIT Clause nhận dự án làm có lương

    SQLite – LIMIT Clause



    SQLite LIMIT clause is used to limit the data amount returned by the SELECT statement.

    Syntax

    Following is the basic syntax of SELECT statement with LIMIT clause.

    SELECT column1, column2, columnN
    FROM table_name
    LIMIT [no of rows]
    

    Following is the syntax of LIMIT clause when it is used along with OFFSET clause.

    SELECT column1, column2, columnN
    FROM table_name
    LIMIT [no of rows] OFFSET [row num]
    

    SQLite engine will return rows starting from the next row to the given OFFSET as shown below in the last example.

    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 limits the row in the table according to the number of rows you want to fetch from table.

    sqlite> SELECT * FROM COMPANY LIMIT 6;
    

    This will produce the following result.

    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
    

    However in certain situations, you may need to pick up a set of records from a particular offset. Here is an example, which picks up 3 records starting from the 3rd position.

    sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 2;
    

    This will produce the following result.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    3           Teddy       23          Norway      20000.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

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

    SQLite – HAVING Clause



    HAVING clause enables you to specify conditions that filter which group results appear in the final results.

    The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by GROUP BY clause.

    Syntax

    Following is the position of HAVING clause in a SELECT query.

    SELECT
    FROM
    WHERE
    GROUP BY
    HAVING
    ORDER BY
    

    HAVING clause must follow GROUP BY clause in a query and must also precede ORDER BY clause if used. Following is the syntax of the SELECT statement, including HAVING clause.

    SELECT column1, column2
    FROM table1, table2
    WHERE [ conditions ]
    GROUP BY column1, column2
    HAVING [ conditions ]
    ORDER BY column1, column2
    

    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
    8           Paul        24          Houston     20000.0
    9           James       44          Norway      5000.0
    10          James       45          Texas       5000.0
    

    Following is the example, which will display the record for which the name count is less than 2.

    sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2;
    

    This will produce the following result.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    2           Allen       25          Texas       15000
    5           David       27          Texas       85000
    6           Kim         22          South-Hall  45000
    4           Mark        25          Rich-Mond   65000
    3           Teddy       23          Norway      20000
    

    Following is the example, which will display the record for which the name count is greater than 2.

    sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2;
    

    This will produce the following result.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    10          James       45          Texas       5000
    

    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 – LIKE Clause nhận dự án làm có lương

    SQLite – LIKE Clause



    SQLite LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. There are two wildcards used in conjunction with the LIKE operator −

    • The percent sign (%)
    • The underscore (_)

    The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations.

    Syntax

    Following is the basic syntax of % and _.

    SELECT FROM table_name
    WHERE column LIKE ''XXXX%''
    or
    SELECT FROM table_name
    WHERE column LIKE ''%XXXX%''
    or
    SELECT FROM table_name
    WHERE column LIKE ''XXXX_''
    or
    SELECT FROM table_name
    WHERE column LIKE ''_XXXX''
    or
    SELECT FROM table_name
    WHERE column LIKE ''_XXXX_''
    

    You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value.

    Example

    Following table lists a number of examples showing WHERE part having different LIKE clause with ”%” and ”_” operators.

    Sr.No. Statement & Description
    1

    WHERE SALARY LIKE ”200%”

    Finds any values that start with 200

    2

    WHERE SALARY LIKE ”%200%”

    Finds any values that have 200 in any position

    3

    WHERE SALARY LIKE ”_00%”

    Finds any values that have 00 in the second and third positions

    4

    WHERE SALARY LIKE ”2_%_%”

    Finds any values that start with 2 and are at least 3 characters in length

    5

    WHERE SALARY LIKE ”%2”

    Finds any values that end with 2

    6

    WHERE SALARY LIKE ”_2%3”

    Finds any values that has a 2 in the second position and ends with a 3

    7

    WHERE SALARY LIKE ”2___3”

    Finds any values in a five-digit number that starts with 2 and ends with 3

    Let us take a real 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 display all the records from COMPANY table where AGE starts with 2.

    sqlite> SELECT * FROM COMPANY WHERE AGE LIKE ''2%
    

    This will produce the following result.

    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       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text.

    sqlite> SELECT * FROM COMPANY WHERE ADDRESS  LIKE ''%-%
    

    This will produce the following result.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    4           Mark        25          Rich-Mond   65000.0
    6           Kim         22          South-Hall  45000.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 – GLOB Clause nhận dự án làm có lương

    SQLite – GLOB Clause



    SQLite GLOB operator is used to match only text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the GLOB operator will return true, which is 1. Unlike LIKE operator, GLOB is case sensitive and it follows syntax of UNIX for specifying THE following wildcards.

    • The asterisk sign (*)
    • The question mark (?)

    The asterisk sign (*) represents zero or multiple numbers or characters. The question mark (?) represents a single number or character.

    Syntax

    Following is the basic syntax of * and ?.

    SELECT FROM table_name
    WHERE column GLOB ''XXXX*''
    or
    SELECT FROM table_name
    WHERE column GLOB ''*XXXX*''
    or
    SELECT FROM table_name
    WHERE column GLOB ''XXXX?''
    or
    SELECT FROM table_name
    WHERE column GLOB ''?XXXX''
    or
    SELECT FROM table_name
    WHERE column GLOB ''?XXXX?''
    or
    SELECT FROM table_name
    WHERE column GLOB ''????''
    

    You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value.

    Example

    Following table lists a number of examples showing WHERE part having different GLOB clause with ”*” and ”?” operators.

    Sr.No. Statement & Description
    1

    WHERE SALARY GLOB ”200*”

    Finds any values that start with 200

    2

    WHERE SALARY GLOB ”*200*”

    Finds any values that have 200 in any position

    3

    WHERE SALARY GLOB ”?00*”

    Finds any values that have 00 in the second and third positions

    4

    WHERE SALARY GLOB ”2??”

    Finds any values that start with 2 and are at least 3 characters in length

    5

    WHERE SALARY GLOB ”*2”

    Finds any values that end with 2

    6

    WHERE SALARY GLOB ”?2*3”

    Finds any values that have a 2 in the second position and end with a 3

    7

    WHERE SALARY GLOB ”2???3”

    Finds any values in a five-digit number that start with 2 and end with 3

    Let us take a real 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 display all the records from COMPANY table, where AGE starts with 2.

    sqlite> SELECT * FROM COMPANY WHERE AGE  GLOB ''2*
    

    This will produce the following result.

    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       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text −

    sqlite> SELECT * FROM COMPANY WHERE ADDRESS  GLOB ''*-*
    

    This will produce the following result.

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    4           Mark        25          Rich-Mond   65000.0
    6           Kim         22          South-Hall  45000.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