{"id":1275,"date":"2023-04-14T09:56:16","date_gmt":"2023-04-14T08:56:16","guid":{"rendered":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/?page_id=1275"},"modified":"2023-08-28T10:27:19","modified_gmt":"2023-08-28T09:27:19","slug":"sql","status":"publish","type":"page","link":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/data-modelling\/sql\/","title":{"rendered":"SQL"},"content":{"rendered":"\n<p>In the last chapter when making the form look nicer you saw the row source that looked like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT &#091;Vehicle].&#091;ID], &#091;Vehicle].&#091;Number Plate], &#091;Vehicle].&#091;Manufacturer], &#091;Vehicle].&#091;Model] FROM &#091;Vehicle] ORDER BY &#091;Manufacturer], &#091;Model], &#091;Number Plate];<\/code><\/pre>\n\n\n\n<p>These SELECT, FROM and ORDER BY keywords are SQL. SQL stands for Structured Query Language.<\/p>\n\n\n\n<p>SQL is designed to query data stored in a relational database.<\/p>\n\n\n\n<p>SQL implementations are similar but not 100% compatible. The syntax you use for MS Access will not be identical to what you would need for MySQL for example.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Constraints<\/h2>\n\n\n\n<p>Constraints specify rules for the data in a table. The following are common constraints.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>CONSTRAINT<\/strong><\/td><td><strong>MEANING<\/strong><\/td><\/tr><tr><td>NOT NULL<\/td><td>Entry cannot be left empty<\/td><\/tr><tr><td>UNIQUE<\/td><td>Entry must be difference from any other in the column<\/td><\/tr><tr><td>PRIMARY KEY<\/td><td>Combination of NOT NULL and UNIQUE<\/td><\/tr><tr><td>FOREIGN KEY<\/td><td>Prevents data being added if this value does not appear in the other table<\/td><\/tr><tr><td>DEFAULT<\/td><td>Sets a value if none given<\/td><\/tr><tr><td>CHECK<\/td><td>Specify conditions that need to be matched to be valid<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Common constraints<\/figcaption><\/figure>\n\n\n\n<p>Simple constraints can be added after the column definition in a CREATE or ALTER statement e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE TABLE Test (ID int PRIMARY KEY, ...<\/code><\/pre>\n\n\n\n<p>Alternatively, or with more complex ones dealing with multiple columns, you add a CONSTRAINT line to the end of the query.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>...\nAge int,\nCONSTRAINT CHK_Age (Age &gt;= 18 AND Age &lt;= 100)...<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Data types<\/h2>\n\n\n\n<p>Up until now you have dealt with either a high level design data type such as Number where Number is any numeric value, or in Access where Number is an small integer by default. In SQL you state the exact data type when creating or altering a table. The most common ones are:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>DATA TYPE<\/strong><\/td><td><strong>DESCRIPTION<\/strong><\/td><\/tr><tr><td>SHORT or INT<\/td><td>Whole number between -32768 and 32767<\/td><\/tr><tr><td>LONG<\/td><td>Whole number between -2147483648 and 2147483647<\/td><\/tr><tr><td>SINGLE<\/td><td>Single precision floating point number<\/td><\/tr><tr><td>DOUBLE<\/td><td>Double precision floating point number<\/td><\/tr><tr><td>VARCHAR(n)<\/td><td>Variable width character string, where n is the max length. n cannot be more than 8000 max characters<\/td><\/tr><tr><td>TINYINT(1) or BIT<\/td><td>0, 1 or NULL used for boolean<\/td><\/tr><tr><td>DATETIME<\/td><td>Store a date and time in ithe format YYYY-MM-DD hh:mm:ss<\/td><\/tr><\/tbody><\/table><figcaption class=\"wp-element-caption\">Common data types<\/figcaption><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Reserved words<\/h2>\n\n\n\n<p>Just like in programming, some words are reserved and must be escaped before they can be used. Each SQL platform is different so search the documentation if you encounter one.<\/p>\n\n\n\n<p>For example, in MySQL you escape a table or column name by enclosing it in backticks, the ` character to the left of the 1 key. Whereas in Access you use the square brackets.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Creating a database<\/h2>\n\n\n\n<p>There are normally two parts to creating a database:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Create the database<\/li>\n\n\n\n<li>Grant access to one or more users<\/li>\n<\/ul>\n\n\n\n<p>In simplest terms, granting one user the same permissions to all tables, for MySQL you would use syntax like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE DATABASE databasename DEFAULT CHARSET charset;\nGRANT permissions ON databasename.* TO 'username'@'hostname' IDENTIFIED BY 'password';<\/code><\/pre>\n\n\n\n<p>Where databasename, charset, permissions, username, hostname and password are all replaced by relevant values e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE DATABASE db_hotel_guests DEFAULT CHARSET utf8;\nGRANT ALL ON db_hotel_guests.* TO 'hotel_admin'@'localhost' IDENTIFIED BY 'j)ks89KIos0Kle,31d';<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Creating a table<\/h2>\n\n\n\n<p>The CREATE TABLE query gives the table a name and then lists the column names, their data type and any constraints e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE TABLE TestLink (\n`ID` INT NOT NULL PRIMARY KEY,\n`Name` VARCHAR(100) NOT NULL,\n`DriverID` INT,\nCONSTRAINT FK_DriverTestLink FOREIGN KEY (`DriverID`) REFERENCES Driver(`ID`)\n);<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Inserting data<\/h2>\n\n\n\n<p>To add a new row to a table you use the INSERT INTO command following the format:<\/p>\n\n\n\n<p>INSERT INTO TableName VALUES (Value1, Value2\u2026);<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>INSERT INTO Driver VALUES (0000000001, 'John', 'Doe', '123 Main Street', 01234567890, 'jdoe@example.com');<\/code><\/pre>\n\n\n\n<p>Some RDBMS allow you to list which columns you want to supply data for. But you would need to include any required field unless they are a field automatically filled by the database such as when using the DEFAULT constraint e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>INSERT INTO Driver (Forename, Surname, Address) VALUES ('John', 'Doe', '123 Main Street');<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Selecting data<\/h2>\n\n\n\n<p>The SELECT \u2026 FROM statement is used to select data from a database.<\/p>\n\n\n\n<p>To select all the records from a table you use an asterisk (*) instead of a column name. For example, to get all the drivers in the Driver table you could use the following SQL:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM Driver;<\/code><\/pre>\n\n\n\n<p>To only view certain columns in the results you replace the * with the column names e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT Forename, Surname FROM Driver;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">SELECT \u2026 FROM \u2026 WHERE Queries<\/h3>\n\n\n\n<p>By adding a WHERE clause to the query you can limit the results to only those that match. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM Driver WHERE Surname = 'Smith';<\/code><\/pre>\n\n\n\n<p>Will return all the columns in the Driver table but only for the rows that have a value of&nbsp; \u2018Smith\u2019 in the Surname column.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Operators<\/h2>\n\n\n\n<p>WHERE queries can be refined using operators. In the previous slide we used = to return matching values. But you can also use &gt; and &lt; for checking greater than and less than comparisons of numeric data e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT ID FROM Invoice WHERE Amount &gt; 500;<\/code><\/pre>\n\n\n\n<p>Queries can be further refined using the AND and OR operators:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>AND will only return a row where both sides of the AND operator are true<\/li>\n\n\n\n<li>OR will only return a row where either side of the OR operator is true<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Ordering the results<\/h2>\n\n\n\n<p>The ORDER BY clause is used to order the results by the given column in the given order. The order being either ascending (ASC) or descending (DESC) e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT Forename, Surname FROM Driver ORDER BY Forename ASC;<\/code><\/pre>\n\n\n\n<p>You can also order by multiple columns e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT Forename, Surname FROM Driver ORDER BY Forename ASC, Surname ASC;<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Wildcards<\/h2>\n\n\n\n<p>Wildcard characters are used with the SQL operator LIKE when you want to match only part of a string or text.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>% denotes a set of characters<\/li>\n\n\n\n<li>_ denotes a single character<\/li>\n<\/ul>\n\n\n\n<p>For MS Access use:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>* instead of %<\/li>\n\n\n\n<li>? instead of _<\/li>\n<\/ul>\n\n\n\n<p>For a=example, to find all the rows of the Driver table where the Surname field begins with Mac you could use a query like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM Driver WHERE Surname LIKE 'Mac%';<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Updating entries<\/h2>\n\n\n\n<p>To edit the data that already exists in a database you use the UPDATE query. This follows the format:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>UPDATE TableName SET ColumnName = Value;<\/code><\/pre>\n\n\n\n<p>But you will&nbsp;<strong>almost always<\/strong>&nbsp;use a WHERE clause to limit the number of rows being changed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>UPDATE TableName SET ColumnName = NewValue WHERE ColumnToMatch = ValueToMatch;<\/code><\/pre>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>UPDATE Driver SET Address = 'Flat 1, 123 Main Street' WHERE ID = 0000000001;<\/code><\/pre>\n\n\n\n<p>This will only change the record with that ID even if there is another driver called John Doe living at 123 Main Street.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Deleting entries<\/h2>\n\n\n\n<p>To remove data from a table you use the DELETE query in the format:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>DELETE FROM TableName;<\/code><\/pre>\n\n\n\n<p>You should&nbsp;<strong>always<\/strong>&nbsp;use a WHERE clause to limit the rows affected:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>DELETE FROM TableName WHERE ColumnToMatch = ValueToMatch;<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Joining tables<\/h2>\n\n\n\n<p>Joins are used to combine the columns from multiple tables into the results of a single query. The most common is the inner join.<\/p>\n\n\n\n<p>An INNER JOIN clause is used to select data from more than one table.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT Driver.Forename, Driver.Surname, Invoice.CreatedDate, Invoice.Amount\nFROM Driver\nINNER JOIN Invoice on Driver.ID = Invoice.DriverID\nWHERE Invoice.Paid = false;<\/code><\/pre>\n\n\n\n<p>You can still use WHERE and ORDER BY clauses with inner joins. The join is simply to combine multiple tables into one temporary table for the purpose of the query.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Functions<\/h2>\n\n\n\n<p>Most RDBMS come with built in functions that can be used in a SELECT statement. Some common functions are:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>FUNCTION NAME<\/strong><\/td><td><strong>MEANING<\/strong><\/td><\/tr><tr><td>AVG()<\/td><td>Returns the average value of a numeric column or expression<\/td><\/tr><tr><td>COUNT()<\/td><td>Returns the number of rows that match the criteria in the WHERE clause<\/td><\/tr><tr><td>MAX()<\/td><td>Returns the largest value of the selected column or expression<\/td><\/tr><tr><td>MIN()<\/td><td>Returns the smallest value of the selected column or expression<\/td><\/tr><tr><td>SUM()<\/td><td>Returns the total sum of a numeric column or expression<\/td><\/tr><tr><td>FORMAT()<\/td><td>Format a value to a given pattern, such as setting the number of decimal places<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Common rdbms functions<\/p>\n\n\n\n<p>Use self learning to find how to use these functions with the database product that you are using. While most are similar, there might be differences between products. Check to be sure.<\/p>\n\n\n\n<p>Because the function returns a single value for the whole column you cannot mix it with a regular select column that would return multiple rows.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT ID, MAX(Amount) FROM Invoice;<\/code><\/pre>\n\n\n\n<p>You can use it in a select statement that contains multiple functions as they each only return one vale.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT COUNT(ID), MAX(Amount) FROM Invoice;<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Aliases<\/h2>\n\n\n\n<p>Aliases allow you to use a different name in your queries from the given table or column name. This is useful if you are dealing with really long names, ambiguous names, or computed column names formed when creating a column from a mathematical equation of other columns.<\/p>\n\n\n\n<p>Long name example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT DriverID As &#091;'dID'], VehicleID As &#091;'vID'] FROM DriverVehicleLink As&#091;'DVl'];<\/code><\/pre>\n\n\n\n<p>Ambiguous name example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT * FROM Table3458687687 As &#091;'FeedbackJune21'];<\/code><\/pre>\n\n\n\n<p>Computed name example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT StartingBalance - Costs As &#091;'CurrentBalance'] FROM PettyCash;<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Grouping results<\/h2>\n\n\n\n<p>The GROUP BY clause groups rows of records together that are identical based on the criteria given. This is useful because you run functions on these groups rather than the entire column e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SELECT COUNT(Make), Make FROM Vehicle GROUP BY Make;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>+-------------------------------+\n| COUNT(Make)       | Make      |\n+-------------------------------+\n|                  3| Ford      |\n|                  5| Renault   |\n|                  1| Tesla     |\n+-------------------------------+<\/code><\/pre>\n\n\n\n<p>You can use ORDER BY and GROUP BY clauses in the same query but the GROUP BY must come before the ORDER BY.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">How to see the SQL in Access<\/h2>\n\n\n\n<p>Click the Create Menu and choose the Query Wizard option. Then choose the \u201cSimple Query Wizard\u201d in the popup.<\/p>\n\n\n\n<p>Use the arrows on the next page to add all the columns to the right-hand box then click Next.<\/p>\n\n\n\n<p>Choose a name for the query and choose the Modify option before clicking finish.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"541\" height=\"288\" src=\"https:\/\/blogs.glowscotland.org.uk\/es\/public\/software\/uploads\/sites\/4063\/2023\/04\/14100648\/DB45.png\" alt=\"Simple Query Wizard button location\" class=\"wp-image-1279\" srcset=\"https:\/\/blogs.glowscotland.org.uk\/es\/public\/software\/uploads\/sites\/4063\/2023\/04\/14100648\/DB45.png 541w, https:\/\/blogs.glowscotland.org.uk\/es\/public\/software\/uploads\/sites\/4063\/2023\/04\/14100648\/DB45-300x160.png 300w\" sizes=\"auto, (max-width: 541px) 100vw, 541px\" \/><figcaption class=\"wp-element-caption\">Simple Query Wizard button location<\/figcaption><\/figure><\/div>\n\n\n<p>On the far left of the Design Ribbon is an option for View. Click this the in the dropdown choose \u201cSQL View\u201d.<\/p>\n\n\n\n<p>You can now create SQL statements. To run the query, click the Run option in the Design ribbon.<\/p>\n\n\n\n<p>If the table that you are adding data to is open, you will need to close and reopen it to see the new data.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"544\" height=\"288\" src=\"https:\/\/blogs.glowscotland.org.uk\/es\/public\/software\/uploads\/sites\/4063\/2023\/04\/14100717\/DB46.png\" alt=\"SQL View option location\" class=\"wp-image-1280\" srcset=\"https:\/\/blogs.glowscotland.org.uk\/es\/public\/software\/uploads\/sites\/4063\/2023\/04\/14100717\/DB46.png 544w, https:\/\/blogs.glowscotland.org.uk\/es\/public\/software\/uploads\/sites\/4063\/2023\/04\/14100717\/DB46-300x159.png 300w\" sizes=\"auto, (max-width: 544px) 100vw, 544px\" \/><figcaption class=\"wp-element-caption\">SQL View option location<\/figcaption><\/figure><\/div>\n\n\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Syntax errors<\/h2>\n\n\n\n<p>As mentioned above, some words are reserved and must be escaped before they can be used. In Access you should surround the word in square brackets [] or rename that column or table.<\/p>\n\n\n\n<p>If you used a column called Note in the previous slide you will have encountered a syntax error when you tried to run the query and Access will have highlighted the word causing the issue. Try escaping it in square brackets [Note].<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the last chapter when making the form look nicer you saw the row source that looked like: These SELECT, FROM and ORDER BY keywords are SQL. SQL stands for Structured Query Language. SQL is designed to query data stored in a relational database. SQL implementations are similar but not 100% compatible. The syntax you&hellip; <a class=\"more-link\" href=\"https:\/\/blogs.glowscotland.org.uk\/es\/software\/data-modelling\/sql\/\">Continue reading <span class=\"screen-reader-text\">SQL<\/span><\/a><\/p>\n","protected":false},"author":5710,"featured_media":0,"parent":1179,"menu_order":6,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1275","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/pages\/1275","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/users\/5710"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/comments?post=1275"}],"version-history":[{"count":3,"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/pages\/1275\/revisions"}],"predecessor-version":[{"id":1353,"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/pages\/1275\/revisions\/1353"}],"up":[{"embeddable":true,"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/pages\/1179"}],"wp:attachment":[{"href":"https:\/\/blogs.glowscotland.org.uk\/es\/software\/wp-json\/wp\/v2\/media?parent=1275"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}