Author: alien

  • Khóa học miễn phí SQL – Text & Image Functions nhận dự án làm có lương

    SQL – Text & Image functions



    SQL Text and Image functions operate on text and image data. The text and image functions are −

    Sr.No. Function & Description
    1

    Returns the pointer value of the text or images.

    2

    Returns an integer value(1 for valid, 0 for non-valid).


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

    SQL – Numeric Functions



    SQL numeric functions are used primarily for numeric manipulation and/or mathematical calculations. The following table details the numeric functions −

    Sr.No. Function & Description
    1

    Returns the absolute value of numeric expression.

    2

    Returns the arccosine of numeric expression. Returns NULL if the value is not in the range -1 to 1.

    3

    Returns the arcsine of numeric expression. Returns NULL if value is not in the range -1 to 1

    4

    Returns the arctangent of numeric expression.

    5

    Returns the arctangent of the two variables passed to it.

    6

    Returns the smallest (closest to negative infinity) integer value that is greater than or equal to this value.

    7

    Returns the trigonometric cosine of the given value.

    8

    Returns the trigonometric cotangent of the given value.

    9

    Returns numeric expression converted from radians to degrees.

    10

    Returns the base of the natural logarithm (e) raised to the power of passed numeric expression.

    11

    Returns the largest integer value that is not greater than passed numeric expression.

    12

    Returns the natural logarithm of the passed numeric expression.

    13

    Returns the base-10 logarithm of the passed numeric expression.

    14

    Returns the value of pi

    15

    Returns the value of one expression raised to the power of another expression

    16

    Returns the value of passed expression converted from degrees to radians.

    17

    Returns the random value between 0 and 1.

    18

    Returns numeric expression rounded to an integer. Can be used to round an expression to a number of decimal points

    19

    Returns the sign of a number, indicating whether it is positive, negative, or zero.

    20

    Returns the sine of numeric expression given in radians.

    21

    Returns the non-negative square root of numeric expression.

    22

    Returns the tangent of numeric expression expressed in radians.


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

    SQL – Aggregate Functions



    In general, aggregation is a consideration of a collection of objects that are bound together as a single entity. SQL provides a set of aggregate functions that perform operations on all the entities of the column of a table considering them as a single unit. Following are the SQL aggregate functions −

    Sr.No. Function & Description
    1

    Returns the approximate number of rows with distinct expression values.

    3

    Returns the checksum value.

    4

    Returns the count of the number of items or rows selected by the select statement.

    6

    Returns whether the specified column expression in a group by list is aggregate or not.

    7

    Returns the level of grouping.

    10

    Returns the statistical standard deviation of the fields (numerical values) in a particular column.

    11

    Returns the population standard deviation for the fields (numerical values) in a particular column.

    13

    Returns the statistical standard variance of the fields (numerical values) in a particular column.

    14

    Returns the population standard variance of the fields (numerical values) in a particular column.


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

    SQL – String Functions



    SQL string functions are used primarily for string manipulation. The following table details the important string functions −

    Sr.No. Function & Description
    1

    Returns numeric value of left-most character

    2

    Returns the character for each integer passed

    3

    Returns the position of a substring within the given string.

    4

    Returns concatenate with separator

    5

    Returns concatenated string

    6

    returns an integer value measuring the difference between the SOUNDEX() values of two different expressions(strings).

    7

    Returns a text with escaped characters.

    8

    Returns the formatted string.

    9

    Returns the extracting string.

    10

    Returns the length of the given string.

    11

    Returns returns the lower case of the given string.

    12

    Returns a string after removing all the white spaces and characters from the string found on the left side.

    13

    Returns the Unicode character based on the number code.

    14

    Returns the position of a pattern in a string.

    15

    Returns a string with a delimiter

    16

    Returns a new string by replacing all the occurrences of the particular part of a string (substring) with a specified string.

    17

    Returns the repeated value.

    18

    Returns a reversed string.

    19

    Returns the rightmost characters from the actual(current) string.

    20

    Returns a string after removing all trailing blanks.

    21

    Returns the Soundex string.

    22

    returns a string consisting of N number of space characters.

    23

    Returns a number as string.

    24

    Concatenates the values of string expressions and places separator values between them.

    25

    Splits a string into rows of substrings.

    26

    Returns a new string by inserting the second expression at the specified deleted place.

    27

    Returns the part of the character.

    28

    Returns a string from the first argument.

    29

    Returns a trimmed string.

    30

    Returns an integer value of the first character.

    31

    returns a string that has all the characters in upper case.


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

    SQL – Date Functions



    The Date & time functions are built-in functions in the SQL server that allows you to manipulate and perform operations on date and time values in the SQL server.

    These functions can be used in SQL Server queries to perform various date and time operations, such as filtering records based on dates, calculating date differences, and formatting dates for display purposes.

    Sr.No. Function & Description
    1

    This function is used to retrieve the first day of the week which is set by the SET DATEFIRST function.

    2

    Is used to retrieve the current date and time.

    3

    This function is used to retrieve the current time zone offset from Coordinated Universal Time (UTC).

    4

    Is used to retrieve the current time zone ID observed by a server or an instance.

    5

    Is used to group data into groups that correspond to fixed periods of time.

    6

    Is used to add a specific number of intervals to a given date or time value.

    7

    Is used to calculate the difference between two date values and returns in a int data type.

    8

    Is used to calculate the difference between two dates values and return in a bigint data type.

    9

    This function is used to retrieve a date from individual segments such as year, month, and day.

    10

    This function is used to retrieve a specified part of a date or time value as string.

    11

    Is used to return a specified part of a date or time value as integer.

    12

    Is used to construct a datetime2 value from an individual date and time segments.

    13

    Is used to construct a datetime value from an individual date and time segments.

    14

    Is used to extract a datetimeoffset value from each of a date”s component parts.

    15

    Is used to truncate a date or time value to a specified datepart (such as year, month, day, etc.).

    16

    This function is used to get the day of the month for a specified date.

    17

    This function is used to get the last day of the month for a specified date value.

    18

    This function is used to get the current database system date and time.

    19

    This function is used to get the current database system UTC date and time.

    20

    Is used to determine whether a value is a valid date or not.

    21

    This function is used to get the month part for a specified date (value can be from 1 to 12).

    22

    Is used to construct a new datetime value from individual segments (such as year, month, etc.).

    23

    This function is used to get datetimeoffset values that has been changed from the stored time zone offset to a given new time zone offset.

    24

    This function is used to get the date and time of the SQL Server.

    25

    This function is used to get a value of DATETIMEOFFSET(7) that provides the current system date and time and also timezone of the SQL server.

    26

    This function is used to get date and time of the computer on which the instance of SQL Server is running.

    27

    Is used to construct a time value from individual segments.

    28

    This function is used to get a datetimeoffset value that is translated from a datetime2 expression.

    29

    This function is used to get an integer number that represents the year of the given date.


    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í SQL – IN vs EXISTS nhận dự án làm có lương

    SQL – IN vs EXISTS

    Table of content


    In SQL, we use the IN operator to simplify queries and reduce the need for multiple OR conditions. It allows us to match a value against a list of values. On the other hand, the EXISTS operator checks whether one or more rows exist in a subquery and returns either true or false based on this condition. If the subquery finds at least one row, the EXISTS operator returns true; otherwise, it returns false.

    The SQL IN Operator

    The IN operator in SQL is used to check if a particular value matches any within a given set. This set of values can be specified individually or obtained from a subquery. We can use the IN operator with the WHERE clause to simplify queries and reduce the use of multiple OR conditions.

    Suppose we have a table named CUSTOMERS and we want to retrieve customer details based on their IDs. In this scenario, we can use the IN operator with the WHERE clause to fetch the details of these specific IDs.

    Syntax

    Following is the syntax of the SQL IN operator −

    SELECT column_name
    FROM table_name
    WHERE column_name
    IN (value1, value2, valueN);
    

    In the above syntax, the column_name matches every value (value1, value2, … valueN). If the matches occur, The IN operators returns true; otherwise, false.

    Example

    First of all, let us create a table named CUSTOMERS using the following query −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now, add records into the above created table using the INSERT INTO statement as shown below −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00),
    (7, ''Muffy'', 24, ''Indore'', 10000.00);
    

    The table will be created as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    The following query retrieves the NAME and SALARY columns from the CUSTOMERS table for rows where the ID is 1, 2, or 3.

    SELECT NAME, SALARY FROM CUSTOMERS WHERE ID IN(1, 2, 3);
    

    Output

    On executing the query above, the output is displayed as −

    Name Salary
    Ramesh 2000.00
    Khilan 1500.00
    Kaushik 2000.00

    The SQL EXISTS Operator

    The EXISTS operator is used to look for the existence of a row in a given table that satisfies a set of criteria. It is a Boolean operator that compares the result of the subquery to an existing record and returns true or false.

    The returned value is true, if the subquery fetches single or multiple records; and false, if no record is matched. EXISTS operator follows the querys efficiency features, i.e. when the first true event is detected, it will automatically stop processing further.

    We can use the EXISTS operator with the SELECT, UPDATE, INSERT and DELETE queries.

    Syntax

    Following is the basic syntax of SQL EXISTS operator −

    SELECT column_name FROM table_name
    WHERE EXISTS (
       SELECT column_name FROM table_name
       WHERE condition
    );
    

    Example

    First of all, consider the CUSTOMERS table, and create another table named EMPLOYEES using the following query −

    CREATE TABLE EMPLOYEES (
       EID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       CITY CHAR (25),
       CONTACT INT,
       PRIMARY KEY (EID)
    );
    

    Now, let us insert some records into the EMPLOYEES table using the INSERT INTO statement as shown below −

    INSERT INTO EMPLOYEES VALUES
    (1, ''Varun'', 32, ''Ahmedabad'', 12345),
    (2, ''Mahesh'', 22, ''Kashmir'', 34235 ),
    (3, ''Suresh'', 43, ''Kerala'', 12355 );
    

    The table will be created as follows −

    EID NAME AGE CITY CONTACT
    1 Varun 32 Ahmedabad 12345
    2 Mahesh 22 Kashmir 34235
    3 Suresh 43 Kerala 12355

    In the following query, we are using the EXISTS operator to fetch the names and ages of CUSTOMERS whose AGE is same as the AGE in the EMPLOYEES table.

    SELECT NAME, AGE
    FROM CUSTOMERS
    WHERE EXISTS(
       SELECT * FROM EMPLOYEES
       WHERE CUSTOMERS.AGE = EMPLOYEES.AGE
    );
    

    Output

    Following is the output of the above query −

    NAME AGE
    Ramesh 32
    Komal 22

    IN vs EXISTS

    Following table summarizes all the differences between IN and EXISTS −

    S.No. IN EXISTS
    1

    It is applied to the SQL query to remove the multiple OR conditions.

    It is used to find whether the data in the subquery truly exist.

    2

    It executes all values contained within the IN block.

    If the value is matched, displays the details of the given value. It will terminate the further process if the condition is met.

    3

    It can be used for the comparison of a null value because it returns true, false, and a null value.

    It cannot be used for the comparison of a null value because it returns only true and false values.

    4

    It can be used with subqueries as well as with values.

    It can be used only with subqueries.

    5

    It executes faster when the subquery is smaller.

    It executes faster when the subquery is larger. Because it is more efficient than IN and returns only a Boolean value.


    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í SQL – Group By vs Order By nhận dự án làm có lương

    SQL – Group By vs Order By

    Table of content


    In SQL, we have two commonly used clauses that help us to manipulate data; Group By clause and Order By clause.

    A Group By clause is used to arrange the identical data/records into groups and the Order By clause is used to sort the data in ascending or descending order.

    The SQL Group By Clause

    Using the GROUP BY clause we can organize the data in a table into groups (based on a column) and perform required calculations on them.

    This clause is often used with the aggregate functions such as MIN(), MAX(), SUM(), AVG(), and COUNT() etc.

    It is often used with the SELECT statement, and it is placed after the WHERE clause or before the HAVING clause. If we use the Order By clause, the Group By clause should precede the Order By clause.

    Syntax

    Following is the syntax of the SQL Group By clause −

    SELECT column_name, aggregate_function() FROM table_name
    WHERE condition GROUP BY column_name;
    

    The aggregate_function() and the WHERE clause are optional in the above syntax.

    Example

    Assume we have created a table named CUSTOMERS that contains records of customers such as NAME, AGE, ADDRESS, and SALARY etc.., using the following CREATE statement −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now, we are inserting values into this table using the INSERT statement as follows −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    The CUSTOMERS table will be created as −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    In the SQL query below, we are using the Group by clause to group the rows based on their salaries from the CUSTOMERS table and counting the number of records in each group −

    SELECT SALARY, COUNT(SALARY) from CUSTOMERS GROUP BY SALARY;
    

    Output

    When we execute the above query, the following result will be displayed −

    SALARY MAX(SALARY)
    2000.00 2
    1500.00 1
    6500.00 1
    8500.00 1
    4500.00 1
    10000.00 1

    The SQL Order By Clause

    The ORDER BY clause is used to sort the query results. This clause is used at the end of a SELECT statement, following the WHERE, HAVING and GROUP BY clauses. We can sort the table column in ascending or descending order with the by specifying the sort order as ASC and DESC respectively. If we do not specify any order, it defaults to ascending order.

    Syntax

    Following is the syntax to sort the column value in ascending/descending order using the SQL ORDER BY clause −

    SELECT column_name FROM table_name ORDER BY ASC/DSC;
    

    Example

    In the following query, we are retrieving the ID and NAME from the CUSTOMERS table and using the ORDER BY clause, we are sorting the names in ascending order.

    SELECT ID, NAME FROM CUSTOMERS ORDER BY NAME;
    

    Output

    When we run the above query, we can see that the resultant table is sorted by name in ascending order.

    ID NAME
    4 Chaitali
    5 Hardik
    3 Kaushik
    2 Khilan
    6 Komal
    7 Muffy
    1 Ramesh

    Example

    In the following example, we are retrieving the NAME, calculating the AVG SALARY, and using the GROUP BY clause to group the table by NAME.

    SELECT NAME, AVG(SALARY) FROM CUSTOMERS GROUP BY NAME;
    

    Output

    When we run the above query, we get the name and average salary. The average salary is the same as the actual salary because there are no two or more than two records with the same name. As a result, the average salary is the same as the actual salary, and the table is grouped by name. as shown in the table below.

    NAME AVG(SALARY)
    Ramesh 2000.000000
    Khilan 1500.000000
    Kaushik 2000.000000
    Chaitali 6500.000000
    Hardik 8500.000000
    Komal 4500.000000
    Muffy 10000.000000

    Example

    In the following example, we are retrieving, NAME, AGE, and SALARY and using the ORDER BY clause to sort the AGE in the ascending order.

    SELECT NAME, AGE, SALARY FROM customers ORDER BY AGE;
    

    Output

    The table generated by the above query is as shown below −

    NAME AGE SALARY
    Komal 22 4500.00
    Kaushik 23 2000.00
    Muffy 24 10000.00
    Khilan 25 1500.00
    Chaitali 25 6500.00
    Hardik 27 8500.00
    Ramesh 32 2000.00

    Group by vs Order by

    Following table summarizes the differences between the Group By clause and Order by clause −

    S.No. Group By Order By
    1

    It is applied to group rows with same values.

    It sorts the columns in either ascending or descending order.

    2

    It could be allowed in the create view statement.

    It is not allowed to create view statement.

    3

    The attribute cannot be assigned to the aggregate function in the Group By statement.

    The attribute can be assigned to the aggregate function in the Order By statement.

    4

    It is always used before the Order by clause in the select statement.

    It is always used after the Group by clause in the select statement.

    5

    Here grouping is done based on the similarity among the rows attribute value.

    Here, the result-set is sorted based on the columns attribute value either ascending or descending order.

    6

    It controls the presentation of the row

    It controls the presentation of the column.

    7

    We can use the aggregate function in the Group by.

    Here its not mandatory to use the aggregate function in the Order by.


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

    SQL – Database Tuning

    Table of content


    SQL Database Tuning

    Database Tuning in SQL is a set of activities performed to optimize a database and prevents it from becoming a bottleneck.

    There are various techniques with which you can configure the optimal performance of a particular database. Database tuning overlaps with query tuning; so, good indexing and avoiding improper queries help in increasing the database efficiency. In addition, increasing storage, updating to latest database versions and investing in a more powerful CPU (if needed) are also some of the general techniques.

    Database Tuning Techniques

    We can implement the following techniques to optimize the performance of a database −

    Database Normalization

    Normalization is the process of removing of duplicate data from a database. We can normalize a database by breaking down larger tables into smaller related tables. This increases the performance of database as it requires less time to retrieve data from small tables instead of one large table.

    Proper Indexes

    In SQL, indexes are the pointers (memory address) to the location of specific data in database. We use indexes in our database to reduce query time, as the database engine can jump to the location of a specific record using its index instead of scanning the entire database.

    Avoid Improper Queries

    Choosing the correct query to retrieve data efficiently also improves the performance of a database. For example, choosing to retrieve an entire table when we only need the data in a single column will unnecessarily increase query time. So, query the database wisely.

    Let us discuss some of the common improper queries made and how to rectify them to optimize the database performance.

    1. Use SELECT fields instead of SELECT (*)

    In large databases, we should always retrieve only the required columns from the database instead of retrieving all the columns, even when they are not needed. We can easily do this by specifying the column names in the SELECT statement instead of using the SELECT (*) statement.

    Example

    Assume we have created a table with name CUSTOMERS in MySQL database using CREATE TABLE statement as shown below −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Following query inserts values into this table using the INSERT statement −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    Let us say we only want the data in ID, NAME and SALARY columns of the CUSTOMERS table. So, we should only specify those three columns in our SELECT statement as shown below −

    SELECT ID, NAME, SALARY FROM CUSTOMERS;
    

    Output

    The output obtained is as shown below −

    ID NAME SALARY
    1 Ramesh 2000.00
    2 Khilan 1500.00
    3 Kaushik 2000.00
    4 Chaitali 6500.00
    5 Hardik 8500.00
    6 Komal 4500.00
    7 Muffy 10000.00

    2. Use Wildcards

    Wildcards (%) are characters that we use to search for data based on patterns. These wildcards paired with indexes only improves performance because the database can quickly find the data that matches the pattern.

    Example

    If we want to retrieve the names of all the customers starting with K from the CUSTOMERS table, then, the following query will provide the quickest result −

    SELECT ID, NAME FROM CUSTOMERS WHERE NAME LIKE ''K%
    

    Output

    Following is the output of the above query −

    ID NAME
    2 Khilan
    3 Kaushik
    6 Komal

    3. Use Explicit Join

    SQL JOINs are used to combine two tables based on a common column. There are two ways of creating a JOIN implicit join and explicit join. Explicit Join notation use the JOIN keyword with the ON clause to join two tables while the implicit join notation does not use the JOIN keyword and works with the WHERE clause.

    Performance wise, they are both on the same level. However, in more complicated cases, the implicit join notation might produce completely different results than intended. Therefore, Explicit Joining is preferred.

    4. Avoid using SELECT DISTINCT

    The DISTINCT operator in SQL is used to retrieve unique records from the database. And on a properly designed database table with unique indexes, we rarely use it.

    But, if we still have to use it on a table, using the GROUP BY clause instead of the DISTINCT keyword shows a better query performance (at least in some databases).

    5. Avoid using Multiple OR

    The OR operator is used to combine multiple conditions when filtering a database. Whenever we use OR in a filter condition each statement is processed separately. This degrades database performance as the entire table must be scanned multiple times to retrieve the data that matches the filter condition.

    Instead, we can use a more optimized solution; by breaking the different OR conditions into separate queries, which can be processed parallelly by the database. Then, the results from these queries can be combined using UNION.

    Example

    For example, let us say we have a requirement of getting the details of all the customers whose age is greater than 25 or whose salary is greater than 2,000. The optimized query would be as show below −

    SELECT ID, NAME FROM CUSTOMERS WHERE AGE > 25
    UNION
    SELECT ID, NAME FROM CUSTOMERS WHERE SALARY > 2000;
    

    Output

    After executing the above code, we get the following output −

    ID NAME
    1 Ramesh
    5 Hardik
    4 Chaitali
    6 Komal
    7 Muffy

    6. Use WHERE instead of HAVING

    The WHERE and HAVING clause are both used to filter data in SQL. However, WHERE clause is more efficient than HAVING. With WHERE clause, only the records that match the condition are retrieved. But with HAVING clause, it first retrieves all the records and then filters them based on a condition. Therefore, the WHERE clause is preferable.

    Database Defragmentation

    When the data is stored in a database, they are placed in contiguous physical locations. In this case, both logical locations and physical locations are in the same order.

    However, when the database tables are altered by deleting or updating the records, indexes are also altered to suit the changes made. This will cause the indexes to be scattered across the storage. Physical locations also lose the contiguous allocation. Thus, reducing the database performance.

    Defragmentation is the solution this problem. It will reorganize/rebuild the logical ordering of the indexes to match the physical ordering. But, this process first analyses the indexes and chooses whether they only need to be reorganized or rebuilt completely.

    Built-In Tuning Tools

    Some databases provide built-in tuning tools to monitor the database performance. For instance, the Oracle database provides the following tuning tools −

    • EXPLAIN − In SQL, the EXPLAIN command give us the order in which a query is executed along with the estimated cost of each step. We can use this to find the query the least cost to optimize the database.

    • tkprof − tkprof is a command that gives us various statistics, such as CPU and I/O usage of a query. By using these statistics, we can tune our queries to reduce CPU and I/O utilization to increase the efficiency of our database.


    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í SQL – Common Table Expression nhận dự án làm có lương

    SQL – Common Table Expression (CTE)

    Table of content


    A Common Table Expression (CTE) can make it easier to manage and write complex queries by making them more readable and simple, like database views and derived tables. We can reuse or rewrite the query by breaking down the complex queries into simple blocks.

    The SQL Common Table Expression

    The WITH clause in MySQL is used to specify a Common Table Expression.

    A Common Table Expression (CTE) in SQL is a one-time result set, i.e. it is a temporary table that exists only during the execution of a single query. It allows us to work with data specifically within that query, such as using it in SELECT, UPDATE, INSERT, DELETE, CREATE, VIEW, OR MERGE statements.

    CTE is temporary because it cannot be stored anywhere for later use; once the query is executed, it is lost.

    The MySQL WITH Clause

    To specify common table expressions, we use WITH clause that consists of one or more comma-separated subclauses. Within each subclause, we can present a subquery that produces a result set and assigns a name to this subquery.

    You cannot use the WITH clause in MySQL versions before 8.0.

    Syntax

    Following is the syntax to create a CTE using WITH clause −

    WITH CTE_NAME (column_name) AS (query)
    SELECT * FROM CTE_NAME;
    

    Where,

    • CTE_NAME − It is the name assigned to the CTE.
    • column_name − It is the column names for the CTE, which can be useful for improving query readability.
    • query − It defines the CTE and it can be any valid SQL query.
    • After defining the CTE, you can reference it in subsequent queries within the same session.

    Example

    Assume we have created a table named CUSTOMERS in MySQL database using CREATE TABLE statement as shown below −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now, we are inserting some records into the above created table −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    The table created is as shown below −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Here, we are creating a Common Table Expression (CTE) named CUSTOMER_AGE that selects all customers with an age of 23. We are then retrieving the ID, NAME, and AGE of these customers from the CTE.

    WITH CUSTOMER_AGE AS (
    SELECT * FROM customers WHERE AGE = 23)
    SELECT ID, NAME, AGE FROM CUSTOMER_AGE;
    

    Output

    Following is the output of the above query −

    ID NAME AGE
    3 Kaushik 23

    CTE from Multiple Tables

    We can also create a Common Table Expression (CTE) that combines data from multiple tables by using JOIN operations within the CTE”s subquery. To do this, we need to use the comma operator to separate each CTE definition, effectively merging them into a single statement.

    Syntax

    Following is the basic syntax for multiple Common Table Expression (CTE) −

    WITH
       CTE_NAME1 (column_name) AS (query),
       CTE_NAME2 (column_name) AS (query)
    SELECT * FROM CTE_NAME1
    UNION ALL
    SELECT * FROM CTE_NAME2;
    

    We can use multiple Common Table Expressions (CTEs) with various SQL operations, such as UNION, UNION ALL, JOIN, INTERSECT, or EXCEPT.

    Example

    In here, we are defining two CTEs namely ”CUSTOMERS_IN_DELHI” and ”CUSTOMERS_IN_MUMBAI” to segregate customers based on their addresses in Delhi and Mumbai. Then, we are using the UNION ALL operator to combine the results from both CTEs into a single result set, retrieving customer information from both cities.

    WITH
    CUSTOMERS_IN_DELHI AS (
       SELECT * FROM CUSTOMERS WHERE ADDRESS = ''Delhi''),
    CUSTOMERS_IN_MUMBAI AS (
       SELECT * FROM CUSTOMERS WHERE ADDRESS = ''Mumbai'')
    SELECT ID, NAME, ADDRESS FROM CUSTOMERS_IN_DELHI
    UNION ALL
    SELECT ID, NAME, ADDRESS FROM CUSTOMERS_IN_MUMBAI;
    

    Output

    Output of the above query is as shown below −

    ID NAME ADDRESS
    2 Khilan Delhi
    4 Chaitali Mumbai

    Recursive CTE

    A common table expression is a query that keeps referring back to its own result in a loop repeatedly until it returns an empty result.

    A recursive query continually iterates across a subset of the data during its execution, and defines itself in a self-referencing manner. This self-referencing mechanism allows it to repeatedly process and expand its results until a stopping condition is met.

    To make a CTE recursive, it must include a UNION ALL statement and provide a second definition of the query that utilizes the CTE itself. This allows the CTE to repeatedly reference to its own results, creating a recursive behaviour in the query.

    Example

    Now, we are using a recursive CTE named recursive_cust to retrieve data from the ”CUSTOMERS” table created above. Initially, we are selecting customers with salaries above 3000 and then recursively appending customers older than 25 to the result set using the UNION ALL operator −

    WITH recursive_cust (ID, NAME, ADDRESS, AGE) AS (
       SELECT ID, NAME, ADDRESS, AGE
       FROM CUSTOMERS
       WHERE SALARY > 3000
       UNION ALL
       SELECT ID, NAME, ADDRESS, AGE
       FROM CUSTOMERS
       WHERE AGE > 25
    )
    SELECT * FROM recursive_cust;
    

    Output

    When the above query is executed, all data from the customers table whose age is greater than 25 or salary is greater than 3000 will be displayed recursively as shown below −

    ID NAME ADDRESS AGE
    4 Chaitali Mumbai 25
    5 Hardik Bhopal 27
    6 Komal Hyderabad 22
    7 Muffy Indore 24
    1 Ramesh Ahmedabad 32
    5 Hardik Bhopal 27

    Example

    In the following query, we are using a recursive CTE named Numbers to generate and display numbers from 1 to 5. The recursive part continually adds 1 to the previous value until it reaches 5, creating a sequence −

    WITH RECURSIVE Numbers AS (
      SELECT 1 AS N
      UNION ALL
      SELECT N + 1 FROM Numbers WHERE N < 5
    )
    SELECT n FROM Numbers;
    

    Output

    After executing the above query, we get the following output −

    N
    1
    2
    3
    4
    5

    Advantages of CTE

    Following are the advantages of the CTE −

    • CTE makes the code maintenance easier.

    • It increases the readability of the code.

    • It increases the performance of the query.

    • CTE allows for the simple implementation of recursive queries.

    Disadvantages of CTE

    Following are the disadvantages of the CTE −

    • CTE can only be referenced once by the recursive member.

    • We cannot use the table variables and CTEs as parameters in a stored procedure.

    • A CTE can be used in place of a view, but a CTE cannot be nested while views can.


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

    SQL – Cursors

    Table of content


    A database cursor solves the problem of impedance mismatch. It acts as a filter between the result of a SQL query and the statements that process this result.

    Cursors in SQL

    A Cursor is a temporary memory that is allocated by the database server at the time of performing the Data Manipulation Language operations on a table, such as INSERT, UPDATE and DELETE etc. It is used to retrieve and manipulate data stored in the SQL table.

    In MySQL, you cannot declare a cursor directly outside of a stored procedure or function. Cursors are generally declared within stored procedures, functions, or blocks of SQL code in MySQL database.

    Using cursors, we can perform multiple operations on each row of a result set, with or without returning the original data.

    Properties of Cursors

    Following are the properties of MySQL Cursors −

    • READ ONLY − We cannot update or modify any records in the table using the MySQL cursors. We can just fetch and process data from a table.

    • Non-Scrollable − We can retrieve records from a table in a single direction, i.e. from the first record or the last. We cannot move backward or jump to a specific position within the result set.

    • Asensitive Cursor − An asensitive cursor operates directly on the actual data in the database, it does not create a copy of the data. If any change is made to the data by other connections, it can affect the data that the cursor is working with.

    In addition to the Asensitive cursor there is another type known as Insensitive Cursor. An insensitive cursor uses a temporary copy of the data. Therefore, these cursors are insensitive (not affected) to the changes that are made in the table.

    Life Cycle of the Cursor

    There are four steps to manage these cursors. Following diagram illustrates the lifecycle of an SQL cursor −

    Cursor Lifecycle

    Now, let us discuss the phases of life cycle of the cursor one-by-one.

    Declare Cursor Statement

    In MySQL we can declare a cursor using the DECLARE statement and associate it with a SELECT statement to retrieve records from a database table.

    However, this SELECT statement associated with a cursor does not use the INTO clause, as it”s purpose is to fetch and process rows rather than assigning values to variables.

    Syntax

    Following is the syntax to declare a cursor in MySQL database −

    DECLARE cursor_name CURSOR FOR select_statement;
    

    Open Cursor Statement

    After declaring a cursor in MySQL, the next step is to open the cursor using the OPEN statement. It initializes the result-set, allowing us to fetch and process rows from the associated SELECT statement in the cursor.

    Syntax

    Following is the syntax to open a cursor in MySQL database −

    OPEN cursor_name;
    

    Fetch Cursor Statement

    Then, we can use the FETCH statement to retrieve the current row pointed by the cursor, and with each FETCH, the cursor moves to the next row in the result set. This allows us to process each row one by one.

    Syntax

    Following is the syntax to fetch a cursor in MySQL database −

    FETCH cursor_name INTO variable_list;
    

    Close Cursor Statement

    Once all the rows are fetched, we must close the cursor to release the memory associated with it. We can do this using the CLOSE statement.

    Syntax

    Following is the syntax to close a cursor in MySQL database −

    CLOSE cursor_name;
    

    Example

    In this example, let us see how to manage a cursor in a stored procedure.

    Assume we have created a table with the name CUSTOMERS using the CREATE TABLE statement as follows −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now, let us insert some records into the CUSTOMERS table using the INSERT statement as follows −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 );
    

    Now, we will create a backup table named ”CUSTOMERS_BACKUP” to store customer data −

    CREATE TABLE CUSTOMERS_BACKUP (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       PRIMARY KEY (ID)
    );
    

    Here, we are creating a stored procedure named FetchCustomers to fetch customer names from the CUSTOMERS table and inserting them one by one into the BACKUP table. We are using a cursor to iterate through the rows and a handler to detect the end of the result-set, ensuring all names are processed −

    DELIMITER //
    CREATE PROCEDURE FetchCustomers()
    BEGIN
       DECLARE done INT DEFAULT FALSE;
       DECLARE customer_id INT;
       DECLARE customer_name VARCHAR(255);
       DECLARE auto_id INT;
    
       -- Declare cursor
       DECLARE MY_CURSOR CURSOR FOR
       SELECT id, name FROM CUSTOMERS;
    
       -- Declare exit handler
       DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    
       -- Open cursor
       OPEN MY_CURSOR;
    
       -- Fetch and insert rows
       read_loop: LOOP
          FETCH MY_CURSOR INTO customer_id, customer_name;
          IF done = 1 THEN
             LEAVE read_loop;
          END IF;
    
          -- Insert the fetched data into the backup table
          INSERT INTO customers_backup VALUES (customer_id, customer_name);
    
          -- Get the last auto-generated ID used in the insertion
          SET auto_id = LAST_INSERT_ID();
    
       END LOOP;
    
        -- Close cursor
        CLOSE MY_CURSOR;
    END //
    DELIMITER ;
    

    Once we create the procedure successfully, we can execute it using the CALL statement as shown below −

    CALL FetchCustomers();
    

    Verification

    You can verify the contents of the CUSTOMERS_BACKUP table using the SELECT statement as shown below −

    SELECT * FROM CUSTOMERS_BACKUP;
    

    The contents of the table would be −

    ID NAME
    1 Ramesh
    2 Khilan
    3 Kaushik
    4 Chaitali

    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