From Clomosy Docs
ClomosyAdmin (talk | contribs) No edit summary |
|||
| (9 intermediate revisions by 2 users not shown) | |||
| Line 2: | Line 2: | ||
SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.<br> | SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.<br> | ||
The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into the following groups based on their nature:br> | |||
These | |||
:<b>DDL - Data Definition Language</b> | |||
<div class="table-responsive"> | |||
{| class="wikitable" | {| class="wikitable" style="border: 2px solid #c3d7e0" | ||
! style="background-color: #c3d7e0"| Command !!style="background-color: #c3d7e0"| Description | |||
| | |||
|- | |- | ||
| | | <b>CREATE</b> || Creates a new table, a view of a table, or other object in the database. | ||
|- | |- | ||
| | | <b>ALTER</b> || Modifies an existing database object, such as a table. | ||
|- | |- | ||
| | | <b>DROP</b> || Deletes an entire table, a view of a table or other objects in the database. | ||
|} | |} | ||
</div> | |||
{| class="wikitable" | :<b>DML - Data Manipulation Language</b> | ||
| | <div class="table-responsive"> | ||
{| class="wikitable" style="border: 2px solid #c3d7e0" | |||
! style="background-color: #c3d7e0"| Command !!style="background-color: #c3d7e0"| Description | |||
|- | |- | ||
| <b>SELECT</b> || Retrieves certain records from one or more tables. | |||
|- | |- | ||
| | | <b>INSERT</b> || Creates a record. | ||
|- | |- | ||
| | | <b>UPDATE</b> || Modifies records. | ||
|- | |- | ||
| | | <b>DELETE</b> || Deletes records. | ||
|} | |} | ||
</div> | |||
<h2> SELECT Statement </h2> | |||
Retrieves rows from the database and enables the selection of one or many rows or columns from one or many tables in SQL Server. The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:<br> | Retrieves rows from the database and enables the selection of one or many rows or columns from one or many tables in SQL Server. The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:<br> | ||
= | <div class="alert alert-ligth border border-3 border-primary-subtle rounded-5 p-4 shadow-sm" role="alert"> | ||
SELECT * FROM tableName | |||
</div> | |||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT column1, column2, ...., columnN FROM table_name; | |||
</div> | |||
<b>Sample:</b><br> | |||
[[File:SELECT.png|framless|500px]]<br> | |||
<br> | |||
<h2> DISTINCT Statement </h2> | |||
The Distinct statement allows the repetitive data in certain columns of the table to be retrieved as one. This operation allows to bring the data in the desired condition in cases where there is too much data in the table.<br> | The Distinct statement allows the repetitive data in certain columns of the table to be retrieved as one. This operation allows to bring the data in the desired condition in cases where there is too much data in the table.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT DISTINCT column1, column2....columnN FROM table_name; | |||
</div> | |||
<b>Sample:</b><br> | |||
<pre> | |||
SELECT DISTINCT City FROM Customers; | |||
</pre> | |||
<h2> WHERE </h2> | |||
Defines the condition to be met for the rows to be returned. There is no limit to the number of predicates that can be included in a search condition.<br> | Defines the condition to be met for the rows to be returned. There is no limit to the number of predicates that can be included in a search condition.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT column1, column2....columnN FROM table_name WHERE CONDITION; | |||
</div> | |||
<b>Sample:</b><br> | |||
In the Products table, fetch those with productPrice 700.<br><br> | In the Products table, fetch those with productPrice 700.<br><br> | ||
[[File:WHERE.png|frameless|500px]] | [[File:WHERE.png|frameless|500px]]<br><br> | ||
<pre> | |||
SELECT * FROM Products WHERE productPrice= '700'; | |||
</pre> | |||
<h2> AND/OR </h2> | |||
<b> AND:</b> Combines two Boolean expressions and returns TRUE when both expressions are TRUE. When more than one logical operator is used in a statement, the AND operators are evaluated first. You can change the order of evaluation by using parentheses.<br><br> | |||
<b> OR: </b> Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators. However, you can change the order of evaluation by using parentheses. OR returns TRUE when either of the conditions is TRUE.<br> | |||
OR: Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators. However, you can change the order of evaluation by using parentheses. OR returns TRUE when either of the conditions is TRUE.<br> | <b>Syntax: </b><br> | ||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT column1, column2....columnN FROM table_name WHERE CONDITION-1 {AND|OR} CONDITION-2; | |||
</div> | |||
<b>Sample:</b><br> | |||
We said to fetch the productName iPhone 11 or productPrice 700 from all the data in the Products table. He brought those who met both of these conditions. If we used the "and" operator, it would return empty.<br><br> | We said to fetch the productName iPhone 11 or productPrice 700 from all the data in the Products table. He brought those who met both of these conditions. If we used the "and" operator, it would return empty.<br><br> | ||
[[File:AND OR.png|frameless|600px]] | [[File:AND OR.png|frameless|600px]]<br><br> | ||
<pre> | |||
SELECT * FROM Products WHERE productPrice= '7000' OR productname = 'iPhone 11'; | |||
</pre> | |||
<h2> IN </h2> | |||
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.<br> | The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT column1, column2....columnN FROM table_name WHERE column_name IN (val-1, val-2,...val-N); | |||
</div> | |||
<b>Sample:</b><br> | |||
Bring the ones with the price 7000 or 5539.<br> | Bring the ones with the price 7000 or 5539.<br> | ||
[[File:IN.png|frameless|600px]] | [[File:IN.png|frameless|600px]]<br><br> | ||
<pre> | |||
SELECT * FROM Products WHERE productPrice IN (7000,5539); | |||
</pre> | |||
<h2> BETWEEN </h2> | |||
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included. <br> | The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included. <br> | ||
=== | <b>Syntax: </b><br> | ||
--- | <div class="alert alert-secondary" role="alert" data-bs-theme="light"> | ||
SELECT column1, column2....columnN FROM table_name WHERE column_name BETWEEN val-1 AND val-2; | |||
</div> | |||
<b>Sample:</b><br> | |||
Bring the ones with prices between 4000-7000.<br><br> | |||
[[File:BETWEEN.png|frameless|600px]]<br><br> | |||
<pre> | |||
SELECT * FROM Products WHERE productPrice BETWEEN 4000 AND 7000; | |||
</pre> | |||
<h2> LIKE </h2> | |||
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: | The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: | ||
* The percent sign (%) represents zero, one, or multiple characters | * The percent sign (%) represents zero, one, or multiple characters | ||
* The underscore sign (_) represents one, single character<br> | * The underscore sign (_) represents one, single character<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT column1, column2....columnN FROM table_name WHERE column_name LIKE { PATTERN }; | |||
</div> | |||
Here are some examples showing different LIKE operators with '%' and '_' wildcards:<br> | Here are some examples showing different LIKE operators with '%' and '_' wildcards:<br> | ||
{| class="wikitable" | |||
! LIKE Operator !! Description | <div class="table-responsive"> | ||
{| class="wikitable" style="border: 2px solid #c3d7e0" | |||
! style="background-color: #c3d7e0"| LIKE Operator !!style="background-color: #c3d7e0"| Description | |||
|- | |- | ||
| WHERE CustomerName LIKE 'a%' || Finds any values that start with "a" | | WHERE CustomerName LIKE 'a%' || Finds any values that start with "a" | ||
| Line 135: | Line 153: | ||
| WHERE ContactName LIKE 'a%o' || Finds any values that start with "a" and ends with "o" | | WHERE ContactName LIKE 'a%o' || Finds any values that start with "a" and ends with "o" | ||
|} | |} | ||
</div> | |||
<b>Sample:</b><br> | |||
In this example, we have performed the operation to fetch all the data that starts with the word Samsung in "productName". Other than that, you can try the data in other ways.<br><br> | |||
[[File:LIKE.png|frameless|600px]]<br><br> | |||
<pre> | |||
SELECT * FROM Products WHERE productName LIKE 'Samsung%'; | |||
</pre> | |||
<h2> ORDER BY </h2> | |||
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.<br> | The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.<br> | ||
* The ASC command is used to sort the data returned in ascending order. | * The ASC command is used to sort the data returned in ascending order. | ||
* The DESC command is used to sort the returned data in descending order.<br> | * The DESC command is used to sort the returned data in descending order.<br> | ||
=== | <b>Syntax: </b><br> | ||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT column1, column2....columnN FROM table_name WHERE CONDITION ORDER BY column_name {ASC|DESC}; | |||
</div> | |||
<b>Sample:</b><br> | |||
Sort the prices in descending order by saying DESC.<br> | |||
[[File:ORDER BY.png|frameless|500px]]<br><br> | |||
<pre> | |||
SELECT * FROM Products ORDER BY productPrice DESC; | |||
</pre> | |||
<h2> GROUP BY </h2> | |||
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.<br> | The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.<br> | ||
The GROUP BY statement is used to divide the table or tables queried together into groups. Its general usage is as follows. The GROUP BY statement is used when calculating by groups, not sorting results like ORDER BY.<br> | |||
These grouped records; | |||
* To find out how many <b>(COUNT)</b> | |||
* Average value of prices within the group <b>(AVG)</b> | |||
* Total <b>(SUM)</b> value | |||
* We can perform operations such as the most expensive <b>(MAX)</b> and the cheapest <b>(MIN)</b> within groups. | |||
Functions such as COUNT, AVG, SUM, MAX, MIN used to perform these operations are called AGGRAGATE functions and are usually used with the GROUP BY statement.<br> | |||
== SQL - Operators | <div class="alert alert-danger" role="alert" data-bs-theme="light"> | ||
<b>NOTE:</b> When grouping, field names written in select must be included in group by. We cannot perform SELECT * while grouping. However, we can perform calculations in the form of SELECT COUNT(*). | |||
</div> | |||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name; | |||
</div> | |||
<b>Sample:</b><br> | |||
[[File:GROUP BY.png|frameless|650px]]<br><br> | |||
<pre> | |||
SELECT SUM(productPrice) as Price FROM Products GROUP BY productPrice; | |||
</pre> | |||
<h2> SQL - Operators </h2> | |||
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations. These Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.<br> | An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations. These Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.<br> | ||
| Line 157: | Line 214: | ||
* Logical operators | * Logical operators | ||
<h3> Arithmetic Operators </h3> | |||
Assume 'variable a' holds 10 and 'variable b' holds 20, then:<br> | Assume 'variable a' holds 10 and 'variable b' holds 20, then:<br> | ||
{| class="wikitable" | <div class="table-responsive"> | ||
! Operator !! Description !! Example | {| class="wikitable" style="border: 2px solid #c3d7e0" | ||
! style="background-color: #c3d7e0"| Operator !!style="background-color: #c3d7e0"| Description !!style="background-color: #c3d7e0"| Example | |||
|- | |- | ||
| + (Addition) || Adds values on either side of the operator. || a + b will give 30 | | + (Addition) || Adds values on either side of the operator. || a + b will give 30 | ||
| Line 174: | Line 232: | ||
| % (Modulus) || Divides left hand operand by right hand operand and returns remainder. || b % a will give 0 | | % (Modulus) || Divides left hand operand by right hand operand and returns remainder. || b % a will give 0 | ||
|} | |} | ||
</div> | |||
<h3> Comparison Operators </h3> | |||
Assume 'variable a' holds 10 and 'variable b' holds 20, then:<br> | Assume 'variable a' holds 10 and 'variable b' holds 20, then:<br> | ||
{| class="wikitable" | <div class="table-responsive"> | ||
! Operator !! Description !! Example | {| class="wikitable" style="border: 2px solid #c3d7e0" | ||
! style="background-color: #c3d7e0"| Operator !!style="background-color: #c3d7e0"| Description !!style="background-color: #c3d7e0"| Example | |||
|- | |- | ||
| = || Checks if the values of two operands are equal or not, if yes then condition becomes true. || (a = b) is not true. | | = || Checks if the values of two operands are equal or not, if yes then condition becomes true. || (a = b) is not true. | ||
| Line 200: | Line 259: | ||
| !> || Checks if the value of left operand is not greater than the value of right operand, if yes then condition becomes true. || (a !> b) is true. | | !> || Checks if the value of left operand is not greater than the value of right operand, if yes then condition becomes true. || (a !> b) is true. | ||
|} | |} | ||
</div> | |||
<h2> Language Elements </h2> | |||
<h3> Control-of-Flow </h3> | |||
<h4> BEGIN...END </h4> | |||
Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed. BEGIN and END are control-of-flow language keywords.<br> | Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed. BEGIN and END are control-of-flow language keywords.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
BEGIN<br> | |||
{ sql_statement | statement_block }<br> | |||
END | |||
</div> | |||
<h4> BREAK </h4> | |||
BREAK exits the current WHILE loop. If the current WHILE loop is nested inside another, BREAK exits only the current loop, and control is given to the next statement in the outer loop. BREAK is usually inside an IF statement.<br> | BREAK exits the current WHILE loop. If the current WHILE loop is nested inside another, BREAK exits only the current loop, and control is given to the next statement in the outer loop. BREAK is usually inside an IF statement.<br> | ||
=== | <b>Syntax: </b><br> | ||
-- | <div class="alert alert-secondary" role="alert" data-bs-theme="light"> | ||
Restarts a WHILE loop. Any statements after the CONTINUE keyword are ignored. CONTINUE is frequently, but not always, opened by an IF test. | BEGIN<br> | ||
-- statement<br> | |||
WHILE Boolean_expression2<br> | |||
BEGIN<br> | |||
IF condition<br> | |||
BREAK;<br> | |||
END<br> | |||
END | |||
</div> | |||
<h4> CONTINUE </h4> | |||
Restarts a WHILE loop. Any statements after the CONTINUE keyword are ignored. CONTINUE is frequently, but not always, opened by an IF test.<br> | |||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
BEGIN<br> | |||
-- statement<br> | |||
WHILE Boolean_expression2<br> | |||
BEGIN<br> | |||
IF condition<br> | |||
CONTINUE;<br> | |||
END<br> | |||
END | |||
</div> | |||
<h4> ELSE(IF...ELSE) </h4> | |||
Applies conditions for the execution of a statement. SQL statement (sql_statement) following the Boolean_expressionis executed if the Boolean_expression evaluates to TRUE. The optional ELSE keyword is an alternate SQL statement that is executed when Boolean_expression evaluates to FALSE or NULL.<br> | Applies conditions for the execution of a statement. SQL statement (sql_statement) following the Boolean_expressionis executed if the Boolean_expression evaluates to TRUE. The optional ELSE keyword is an alternate SQL statement that is executed when Boolean_expression evaluates to FALSE or NULL.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
IF Boolean_expression <br> | |||
{ sql_statement | statement_block }<br> | |||
[ ELSE <br> | |||
{ sql_statement | statement_block } ] | |||
</div> | |||
<h4> GOTO </h4> | |||
Alters the flow of execution to a label. The SQL statement or statements that follow GOTO are skipped and processing continues at the label. GOTO statements and labels can be used anywhere within a procedure, batch, or statement block. GOTO statements can be nested.<br> | Alters the flow of execution to a label. The SQL statement or statements that follow GOTO are skipped and processing continues at the label. GOTO statements and labels can be used anywhere within a procedure, batch, or statement block. GOTO statements can be nested.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
Define the label:<br> | |||
label: <br> | |||
Alter the execution:<br> | |||
GOTO label | |||
</div> | |||
<h4> RETURN </h4> | |||
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.<br> | |||
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed. | |||
=== | <b>Syntax: </b><br> | ||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
RETURN [ integer_expression ] | |||
</div> | |||
<h4> TRY...CATCH </h4> | |||
Implements error handling for Transact-SQL that is similar to the exception handling in the Microsoft Visual C# and Microsoft Visual C++ languages. A group of Transact-SQL statements can be enclosed in a TRY block. If an error occurs in the TRY block, control is usually passed to another group of statements that is enclosed in a CATCH block.<br> | Implements error handling for Transact-SQL that is similar to the exception handling in the Microsoft Visual C# and Microsoft Visual C++ languages. A group of Transact-SQL statements can be enclosed in a TRY block. If an error occurs in the TRY block, control is usually passed to another group of statements that is enclosed in a CATCH block.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
BEGIN TRY <br> | |||
{ sql_statement | statement_block } <br> | |||
END TRY <br> | |||
BEGIN CATCH <br> | |||
[ { sql_statement | statement_block } ]<br> | |||
END CATCH | |||
[ ; ] | |||
Is a combination of symbols and operators that the SQL Server Database Engine evaluates to obtain a single data value. Simple expressions can be a single constant, variable, column, or scalar function. Operators can be used to join two or more simple expressions into a complex expression. | </div> | ||
<h3> Expressions </h3> | |||
Is a combination of symbols and operators that the SQL Server Database Engine evaluates to obtain a single data value. Simple expressions can be a single constant, variable, column, or scalar function. Operators can be used to join two or more simple expressions into a complex expression.<br> | |||
<h4> CASE </h4> | |||
Evaluates a list of conditions and returns one of multiple possible result expressions.<br> | Evaluates a list of conditions and returns one of multiple possible result expressions.<br> | ||
The CASE expression has two formats:<br> | The CASE expression has two formats:<br> | ||
| Line 277: | Line 357: | ||
Both formats support an optional ELSE argument.<br> | Both formats support an optional ELSE argument.<br> | ||
CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING. | CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.<br> | ||
=== | <b>Syntax: </b><br> | ||
---- | <div class="alert alert-secondary" role="alert" data-bs-theme="light"> | ||
--Simple CASE expression: <br> | |||
CASE input_expression <br> | |||
WHEN when_expression THEN<br> result_expression [ ...n ] <br> | |||
[ ELSE else_result_expression ]<br> | |||
END <br> | |||
--Searched CASE expression: <br> | |||
CASE <br> | |||
WHEN Boolean_expression THEN result_expression [ ...n ] <br> | |||
[ ELSE else_result_expression ] <br> | |||
END | |||
</div> | |||
== Functions | <h4> NULLIF </h4> | ||
Returns a null value if the two specified expressions are equal. For example, SELECT NULLIF(4,4) AS Same, NULLIF(5,7) AS Different; returns NULL for the first column (4 and 4) because the two input values are the same. The second column returns the first value (5) because the two input values are different.<br> | |||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
NULLIF ( expression , expression ) | |||
This function adds a number (a signed integer) to a datepart of an input date, and returns a modified date/time value. For example, you can use this function to find the date that is 7000 minutes from today: number = 7000, datepart = minute, date = today.< | </div> | ||
<h2> Functions </h2> | |||
<h3> Date & Time </h3> | |||
The part of date to which DATEADD adds an integer number. This table lists all valid datepart arguments. | <h4> DATEADD </h4> | ||
{| class="wikitable" | This function adds a number (a signed integer) to a datepart of an input date, and returns a modified date/time value. For example, you can use this function to find the date that is 7000 minutes from today: number = 7000, datepart = minute, date = today.<br> | ||
! datepart !! Abbreviations | |||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
DATEADD (datepart , number , date ) | |||
</div> | |||
<i>datepart;</i><br> | |||
The part of date to which DATEADD adds an integer number. This table lists all valid datepart arguments.<br> | |||
<div class="table-responsive"> | |||
{| class="wikitable" style="border: 2px solid #c3d7e0" | |||
! style="background-color: #c3d7e0"| datepart !!style="background-color: #c3d7e0"| Abbreviations | |||
|- | |- | ||
| year || yy, yyyy | | year || yy, yyyy | ||
| Line 335: | Line 424: | ||
| nanosecond || ns | | nanosecond || ns | ||
|} | |} | ||
</div> | |||
<i>number;</i><br> | |||
An expression that can resolve to an int that DATEADD adds to a datepart of date. DATEADD accepts user-defined variable values for number. DATEADD will truncate a specified number value that has a decimal fraction. It will not round the number value in this situation.<br> | An expression that can resolve to an int that DATEADD adds to a datepart of date. DATEADD accepts user-defined variable values for number. DATEADD will truncate a specified number value that has a decimal fraction. It will not round the number value in this situation.<br> | ||
<i>date;</i><br> | |||
An expression that can resolve to one of the following values:<br> | An expression that can resolve to one of the following values:<br> | ||
| Line 348: | Line 440: | ||
For date, DATEADD will accept a column expression, expression, string literal, or user-defined variable. A string literal value must resolve to a datetime. Use four-digit years to avoid ambiguity issues. <br> | For date, DATEADD will accept a column expression, expression, string literal, or user-defined variable. A string literal value must resolve to a datetime. Use four-digit years to avoid ambiguity issues. <br> | ||
<h4> DATEDIFF </h4> | |||
This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.<br> | This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.<br> | ||
=== | <b>Syntax: </b><br> | ||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
DATEDIFF ( datepart , startdate , enddate ) | |||
</div> | |||
<h4> DAY </h4> | |||
This function returns an integer that represents the day (day of the month) of the specified date.<br> | This function returns an integer that represents the day (day of the month) of the specified date.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
DAY ( date ) | |||
</div> | |||
=== | <h4> GETDATE </h4> | ||
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.<br> | |||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
GETDATE() | |||
</div> | |||
<h4> MONTH </h4> | |||
Returns an integer that represents the month of the specified date.<br> | Returns an integer that represents the month of the specified date.<br> | ||
=== | <b>Syntax: </b><br> | ||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
MONTH ( date ) | |||
</div> | |||
<h4> SYSDATETIME </h4> | |||
Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running.<br> | Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running.<br> | ||
=== | <b>Syntax: </b><br> | ||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
SYSDATETIME ( ) | |||
</div> | |||
<h4> YEAR </h4> | |||
Returns an integer that represents the year of the specified date.<br> | Returns an integer that represents the year of the specified date.<br> | ||
=== ISNULL | <b>Syntax: </b><br> | ||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
YEAR( date ) | |||
</div> | |||
<h3> ISNULL </h3> | |||
Replaces NULL with the specified replacement value.<br> | Replaces NULL with the specified replacement value.<br> | ||
<b>Syntax: </b><br> | |||
<div class="alert alert-secondary" role="alert" data-bs-theme="light"> | |||
ISNULL ( check_expression , replacement_value ) | |||
</div> | |||
<i>check_expression;</i><br> | |||
The expression is to be checked for NULL. check_expression can be of any type.<br> | The expression is to be checked for NULL. check_expression can be of any type.<br> | ||
<i>replacement_value ;</i><br> | |||
Is the expression to be returned if check_expression is NULL. replacement_value must be of a type that is implicitly convertible to the type of check_expression.<br><br> | Is the expression to be returned if check_expression is NULL. replacement_value must be of a type that is implicitly convertible to the type of check_expression.<br><br> | ||
< | <div class="alert alert-ligth border border-3 border-primary-subtle rounded-5 p-4 shadow-sm" role="alert"> | ||
<strong>Notice:</strong> [https://learn.microsoft.com/en-us/sql/sql-server/ Click] if you want to access more information. | |||
</div> | |||
{{#seo:|title=SQL Language Tutorial - Clomosy Docs}} | |||
{{#seo:|description=Learn about SQL Language in Clomosy. A guide to mastering SQL syntax and commands for efficient database management in mobile apps.}} | |||
Latest revision as of 12:58, 24 December 2024
SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.
The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into the following groups based on their nature:br>
- DDL - Data Definition Language
| Command | Description |
|---|---|
| CREATE | Creates a new table, a view of a table, or other object in the database. |
| ALTER | Modifies an existing database object, such as a table. |
| DROP | Deletes an entire table, a view of a table or other objects in the database. |
- DML - Data Manipulation Language
| Command | Description |
|---|---|
| SELECT | Retrieves certain records from one or more tables. |
| INSERT | Creates a record. |
| UPDATE | Modifies records. |
| DELETE | Deletes records. |
SELECT Statement
Retrieves rows from the database and enables the selection of one or many rows or columns from one or many tables in SQL Server. The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:
SELECT * FROM tableName
Syntax:
SELECT column1, column2, ...., columnN FROM table_name;
DISTINCT Statement
The Distinct statement allows the repetitive data in certain columns of the table to be retrieved as one. This operation allows to bring the data in the desired condition in cases where there is too much data in the table.
Syntax:
SELECT DISTINCT column1, column2....columnN FROM table_name;
Sample:
SELECT DISTINCT City FROM Customers;
WHERE
Defines the condition to be met for the rows to be returned. There is no limit to the number of predicates that can be included in a search condition.
Syntax:
SELECT column1, column2....columnN FROM table_name WHERE CONDITION;
Sample:
In the Products table, fetch those with productPrice 700.
![]()
SELECT * FROM Products WHERE productPrice= '700';
AND/OR
AND: Combines two Boolean expressions and returns TRUE when both expressions are TRUE. When more than one logical operator is used in a statement, the AND operators are evaluated first. You can change the order of evaluation by using parentheses.
OR: Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators. However, you can change the order of evaluation by using parentheses. OR returns TRUE when either of the conditions is TRUE.
Syntax:
SELECT column1, column2....columnN FROM table_name WHERE CONDITION-1 {AND|OR} CONDITION-2;
Sample:
We said to fetch the productName iPhone 11 or productPrice 700 from all the data in the Products table. He brought those who met both of these conditions. If we used the "and" operator, it would return empty.
![]()
SELECT * FROM Products WHERE productPrice= '7000' OR productname = 'iPhone 11';
IN
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.
Syntax:
SELECT column1, column2....columnN FROM table_name WHERE column_name IN (val-1, val-2,...val-N);
Sample:
Bring the ones with the price 7000 or 5539.
![]()
SELECT * FROM Products WHERE productPrice IN (7000,5539);
BETWEEN
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.
Syntax:
SELECT column1, column2....columnN FROM table_name WHERE column_name BETWEEN val-1 AND val-2;
Sample:
Bring the ones with prices between 4000-7000.
![]()
SELECT * FROM Products WHERE productPrice BETWEEN 4000 AND 7000;
LIKE
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator:
- The percent sign (%) represents zero, one, or multiple characters
- The underscore sign (_) represents one, single character
Syntax:
SELECT column1, column2....columnN FROM table_name WHERE column_name LIKE { PATTERN };
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
| LIKE Operator | Description |
|---|---|
| WHERE CustomerName LIKE 'a%' | Finds any values that start with "a" |
| WHERE CustomerName LIKE '%a' | Finds any values that end with "a" |
| WHERE CustomerName LIKE '%or%' | Finds any values that have "or" in any position |
| WHERE CustomerName LIKE '_r%' | Finds any values that have "r" in the second position |
| WHERE CustomerName LIKE 'a_%' | Finds any values that start with "a" and are at least 2 characters in length |
| WHERE CustomerName LIKE 'a__%' | Finds any values that start with "a" and are at least 3 characters in length |
| WHERE ContactName LIKE 'a%o' | Finds any values that start with "a" and ends with "o" |
Sample:
In this example, we have performed the operation to fetch all the data that starts with the word Samsung in "productName". Other than that, you can try the data in other ways.
![]()
SELECT * FROM Products WHERE productName LIKE 'Samsung%';
ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.
- The ASC command is used to sort the data returned in ascending order.
- The DESC command is used to sort the returned data in descending order.
Syntax:
SELECT column1, column2....columnN FROM table_name WHERE CONDITION ORDER BY column_name {ASC|DESC};
Sample:
Sort the prices in descending order by saying DESC.
![]()
SELECT * FROM Products ORDER BY productPrice DESC;
GROUP BY
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
The GROUP BY statement is used to divide the table or tables queried together into groups. Its general usage is as follows. The GROUP BY statement is used when calculating by groups, not sorting results like ORDER BY.
These grouped records;
- To find out how many (COUNT)
- Average value of prices within the group (AVG)
- Total (SUM) value
- We can perform operations such as the most expensive (MAX) and the cheapest (MIN) within groups.
Functions such as COUNT, AVG, SUM, MAX, MIN used to perform these operations are called AGGRAGATE functions and are usually used with the GROUP BY statement.
NOTE: When grouping, field names written in select must be included in group by. We cannot perform SELECT * while grouping. However, we can perform calculations in the form of SELECT COUNT(*).
Syntax:
SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name;
SELECT SUM(productPrice) as Price FROM Products GROUP BY productPrice;
SQL - Operators
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations. These Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.
- Arithmetic operators
- Comparison operators
- Logical operators
Arithmetic Operators
Assume 'variable a' holds 10 and 'variable b' holds 20, then:
| Operator | Description | Example |
|---|---|---|
| + (Addition) | Adds values on either side of the operator. | a + b will give 30 |
| - (Subtraction) | Subtracts right hand operand from left hand operand. | a - b will give -10 |
| * (Multiplication) | Multiplies values on either side of the operator. | a * b will give 200 |
| / (Division) | Divides left hand operand by right hand operand. | b / a will give 2 |
| % (Modulus) | Divides left hand operand by right hand operand and returns remainder. | b % a will give 0 |
Comparison Operators
Assume 'variable a' holds 10 and 'variable b' holds 20, then:
| Operator | Description | Example |
|---|---|---|
| = | Checks if the values of two operands are equal or not, if yes then condition becomes true. | (a = b) is not true. |
| != | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (a != b) is true. |
| <> | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (a <> b) is true. |
| > | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (a > b) is not true. |
| < | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (a < b) is true. |
| >= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (a >= b) is not true. |
| <= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (a <= b) is true. |
| !< | Checks if the value of left operand is not less than the value of right operand, if yes then condition becomes true. | (a !< b) is false. |
| !> | Checks if the value of left operand is not greater than the value of right operand, if yes then condition becomes true. | (a !> b) is true. |
Language Elements
Control-of-Flow
BEGIN...END
Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed. BEGIN and END are control-of-flow language keywords.
Syntax:
BEGIN
{ sql_statement | statement_block }
END
BREAK
BREAK exits the current WHILE loop. If the current WHILE loop is nested inside another, BREAK exits only the current loop, and control is given to the next statement in the outer loop. BREAK is usually inside an IF statement.
Syntax:
BEGIN
-- statement
WHILE Boolean_expression2
BEGIN
IF condition
BREAK;
END
END
CONTINUE
Restarts a WHILE loop. Any statements after the CONTINUE keyword are ignored. CONTINUE is frequently, but not always, opened by an IF test.
Syntax:
BEGIN
-- statement
WHILE Boolean_expression2
BEGIN
IF condition
CONTINUE;
END
END
ELSE(IF...ELSE)
Applies conditions for the execution of a statement. SQL statement (sql_statement) following the Boolean_expressionis executed if the Boolean_expression evaluates to TRUE. The optional ELSE keyword is an alternate SQL statement that is executed when Boolean_expression evaluates to FALSE or NULL.
Syntax:
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
GOTO
Alters the flow of execution to a label. The SQL statement or statements that follow GOTO are skipped and processing continues at the label. GOTO statements and labels can be used anywhere within a procedure, batch, or statement block. GOTO statements can be nested.
Syntax:
Define the label:
label:
Alter the execution:
GOTO label
RETURN
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.
Syntax:
RETURN [ integer_expression ]
TRY...CATCH
Implements error handling for Transact-SQL that is similar to the exception handling in the Microsoft Visual C# and Microsoft Visual C++ languages. A group of Transact-SQL statements can be enclosed in a TRY block. If an error occurs in the TRY block, control is usually passed to another group of statements that is enclosed in a CATCH block.
Syntax:
BEGIN TRY
{ sql_statement | statement_block }
END TRY
BEGIN CATCH
[ { sql_statement | statement_block } ]
END CATCH
[ ; ]
Expressions
Is a combination of symbols and operators that the SQL Server Database Engine evaluates to obtain a single data value. Simple expressions can be a single constant, variable, column, or scalar function. Operators can be used to join two or more simple expressions into a complex expression.
CASE
Evaluates a list of conditions and returns one of multiple possible result expressions.
The CASE expression has two formats:
- The simple CASE expression compares an expression to a set of simple expressions to determine the result.
- The searched CASE expression evaluates a set of Boolean expressions to determine the result.
Both formats support an optional ELSE argument.
CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.
Syntax:
--Simple CASE expression:
CASE input_expression
WHEN when_expression THEN
result_expression [ ...n ]
[ ELSE else_result_expression ]
END
--Searched CASE expression:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
NULLIF
Returns a null value if the two specified expressions are equal. For example, SELECT NULLIF(4,4) AS Same, NULLIF(5,7) AS Different; returns NULL for the first column (4 and 4) because the two input values are the same. The second column returns the first value (5) because the two input values are different.
Syntax:
NULLIF ( expression , expression )
Functions
Date & Time
DATEADD
This function adds a number (a signed integer) to a datepart of an input date, and returns a modified date/time value. For example, you can use this function to find the date that is 7000 minutes from today: number = 7000, datepart = minute, date = today.
Syntax:
DATEADD (datepart , number , date )
datepart;
The part of date to which DATEADD adds an integer number. This table lists all valid datepart arguments.
| datepart | Abbreviations |
|---|---|
| year | yy, yyyy |
| quarter | qq, q |
| month | mm, m |
| dayofyear | dy, y |
| day | dd, d |
| week | wk, ww |
| weekday | dw, w |
| hour | hh |
| minute | mi, n |
| second | ss, s |
| millisecond | ms |
| microsecond | mcs |
| nanosecond | ns |
number;
An expression that can resolve to an int that DATEADD adds to a datepart of date. DATEADD accepts user-defined variable values for number. DATEADD will truncate a specified number value that has a decimal fraction. It will not round the number value in this situation.
date;
An expression that can resolve to one of the following values:
- date
- datetime
- datetimeoffset
- datetime2
- smalldatetime
- time
For date, DATEADD will accept a column expression, expression, string literal, or user-defined variable. A string literal value must resolve to a datetime. Use four-digit years to avoid ambiguity issues.
DATEDIFF
This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.
Syntax:
DATEDIFF ( datepart , startdate , enddate )
DAY
This function returns an integer that represents the day (day of the month) of the specified date.
Syntax:
DAY ( date )
GETDATE
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
Syntax:
GETDATE()
MONTH
Returns an integer that represents the month of the specified date.
Syntax:
MONTH ( date )
SYSDATETIME
Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running.
Syntax:
SYSDATETIME ( )
YEAR
Returns an integer that represents the year of the specified date.
Syntax:
YEAR( date )
ISNULL
Replaces NULL with the specified replacement value.
Syntax:
ISNULL ( check_expression , replacement_value )
check_expression;
The expression is to be checked for NULL. check_expression can be of any type.
replacement_value ;
Is the expression to be returned if check_expression is NULL. replacement_value must be of a type that is implicitly convertible to the type of check_expression.
Notice: Click if you want to access more information.