15 Jun 2023 Dominika Florczykowska An Overview of MySQL Window Functions MySQL window functions are very helpful when you want to create meaningful reports with SQL. In this article, we’ll demonstrate the most common window functions in MySQL and explain how to use them. MySQL 8.0 introduced a new feature: window functions. These functions are very useful to data analysts and anyone who creates reports using MySQL. Using them, you can easily compute moving averages, cumulative sums, and other calculations over specified subsets of your data. Read more 5 Jun 2023 LearnSQL.com Team MySQL Cheat Sheet Welcome to the MySQL cheat sheet! Whether you're just starting out with MySQL or you're a seasoned professional looking for a quick reference, this guide is tailor-made for you. This MySQL Cheat Sheet provides a concise and handy reference to the most commonly used MySQL commands and functionalities. It spans a range of topics, from connecting to a MySQL server and managing database contents, to the basic syntax for table creation and modification. Read more 21 Mar 2023 Kamila Ostrowska Best MySQL Courses for Beginners SQL is among the most important languages when it comes to dealing with huge amounts of data. If your job includes analyzing or collecting data and you feel that an Excel file is not enough, you need to learn or develop your SQL skills. And if you learn SQL, you also need to know one of its most popular dialects - MySQL. If you've made the decision to learn SQL, you've come to the right place. Read more 22 Nov 2022 Martyna Sławińska How to Export Data from MySQL into a CSV File A database is a primary platform for working with data and storing data. But often, you must take your data out of the database. Read on to find out how to export data from MySQL database into a CSV file. In this article, we’ll demonstrate how to export data into a CSV file. We’ll start by introducing what a CSV file is and why we use it. Then, we’ll export data from a MySQL database into a CSV file. Read more 13 Sep 2022 Tihomir Babic Top 10 MySQL Interview Questions And Answers You learned SQL and now you want to use this valuable skill to get a better job. Now it’s time to prepare for the job interview. We’ve got ten MySQL interview questions and answers to help you with that. In today's hyperconnected world, knowing how to deal with it has become a necessary skill. That’s why you probably learned (or want to learn) SQL: either your job requires it or you realized that you need SQL to get a better job. Read more 7 Jul 2022 Tihomir Babic An Overview of SQL Text Functions in MySQL Do you work in MySQL as a data analyst? Then you should know how to use its text functions – data analysts don’t work only with numbers. Reporting requires computations, data classification, and label creation, and you can do all of that in MySQL. In this article, I’ll explain several of the most common and useful MySQL text functions by discussing what they do and showing how they do it. Read more 26 Apr 2022 Kamila Ostrowska Top 5 MySQL Query Tools Are you looking for a software solution that will make working with the MySQL database even easier? In this article, I’ll tell you about five highly recommended query tools that will save you time. MySQL may already be familiar to you as the most popular open-source relational database management system (DBMS). It works in most applications, which is why the last Stack Overflow report rated MySQL as the most used database. Read more 22 Feb 2022 Dominika Florczykowska An Overview of MySQL Data Types What data types are available in a MySQL database? In this article, you’ll learn about numeric data types, text data types, and much more! You may have seen our article about data types in SQL. Here, we focus on the MySQL data types. We will discuss the most commonly used ones: numeric, text, and date and time. If you are interested in the topic, be sure to check out our Data Types in SQL course. Read more 27 Oct 2021 Kateryna Koidan SQL Date and Time Functions in 5 Popular SQL Dialects Are you confused by all the date and time functions used across different SQL dialects? In this article, I summarize the date and time data types used in PostgreSQL, Oracle, SQLite, MySQL, and T-SQL. I also provide examples with the key SQL date and time functions used across these dialects. It’s time to become date and time gurus! Do you want to calculate how often employees are running late for work? Read more 17 Aug 2017 Francisco Claria Referential Constraints and Foreign Keys in MySQL Foreign keys and referential constraints allow you to set relationships between tables and modify some of the database engine’s actions. This beginner’s guide explains referential integrity and foreign key use in MySQL. One of the most important aspects of database usage is being able to trust the information you store. Database engines provide several features that help you maintain the quality of your data, like defining required columns as NOT NULL and setting an exact data type for each column. Read more 31 Dec 2014 Agnieszka Kozubek-Krycuń MySQL Collations List Collations To list all collations available in MySQL, use SHOW COLLATION; +-------------------+----------+-----+---------+----------+---------+ | Collation | Charset | Id | Default | Compiled | Sortlen | +-------------------+----------+-----+---------+----------+---------+ | big5_chinese_ci | big5 | 1 | Yes | Yes | 1 | | big5_bin | big5 | 84 | | Yes | 1 | | dec8_swedish_ci | dec8 | 3 | Yes | Yes | 1 | | dec8_bin | dec8 | 69 | | Yes | 1 | | cp850_general_ci | cp850 | 4 | Yes | Yes | 1 | | cp850_bin | cp850 | 80 | | Yes | 1 | | hp8_english_ci | hp8 | 6 | Yes | Yes | 1 | | hp8_bin | hp8 | 72 | | Yes | 1 | | koi8r_general_ci | koi8r | 7 | Yes | Yes | 1 | | koi8r_bin | koi8r | 74 | | Yes | 1 | | latin1_german1_ci | latin1 | 5 | | Yes | 1 | | latin1_swedish_ci | latin1 | 8 | Yes | Yes | 1 | | latin1_danish_ci | latin1 | 15 | | Yes | 1 | | latin1_german2_ci | latin1 | 31 | | Yes | 2 | | latin1_bin | latin1 | 47 | | Yes | 1 | | latin1_general_ci | latin1 | 48 | | Yes | 1 | . Read more 26 Aug 2014 Patrycja Dybka SQL vs. Mongo query In recent times, NoSQL databases have become a hot topic and have gained a crowd of advocates. Indeed, when NoSQL database started to arise, SQL-to-NoSQL converters arose with them as well. But unfortunately, thanks to the code conversion possibility, SQL supporters gained unquestionable evidence that in many cases the good, old SQL is much easier to use. Especially when it comes to queries. I performed a quick Google search and found plenty of nice converter tools. Read more 7 Jan 2014 Agnieszka Kozubek-Krycuń MySQL's group_concat Equivalents in PostgreSQL, Oracle, DB2, HSQLDB, and SQLite The GROUP_CONCAT() function in MySQL MySQL has a very handy function which concatenates strings from a group into one string. For example, let's take a look at the children table with data about parents' and children's names. if (typeof VertabeloEmbededObject === 'undefined') {var VertabeloEmbededObject = "loading";var s=document.createElement("script");s.setAttribute("type","text/javascript");s.setAttribute("src", "https://my.vertabelo.com/js/public-model/v1/api.js");(document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(s);} parent_name child_name John Tom Michael Sylvie John Anna Michael Sophie To get the names of children of each person as a comma-separated string, you use the GROUP_CONCAT() function as follows: Read more 1 Jan 0001 What’s the Difference Between RANK and DENSE_RANK in SQL? Problem: You want to compare the rankings produced by RANK and DENSE_RANK and add them as new columns to a table. Example: Our database has a table named sales_assistant with data in the following columns: id (primary key), first_name, last_name, month, and sold products. idfirst_namelast_namemonthsold products 1LisaBlack 52300 2MaryJacobs52400 3LisaBlack 62700 4MaryJacobs62700 5AlexSmith 62900 6MaryJacobs71200 7LisaBlack 71200 8AlexSmith 71000 Let’s display each sales assistant’s first and last name and number of sold products. Read more 1 Jan 0001 How to make a column unique in SQL? Problem: You would like to make a given column unique in a given table in a database. Example: We would like to make the column name unique in the table product. The query below presents one way to do it. Solution 1 CREATE TABLE product ( id INT NOT NULL PRIMARY KEY, name VARCHAR(100) UNIQUE, producer VARCHAR(100), category VARCHAR(100) ); Discussion: In this example a given column (the column name) was made unique by adding the clause UNIQUE at the end of the definition column (name VARCHAR(100) UNIQUE). Read more 1 Jan 0001 How to Use LIKE in SQL Problem: You’d like to find a substring matching a pattern in a string. Example: Our database has a table named customer with data in the following columns: id, first_name, last_name, and city. idfirst_namelast_namecity 1AlanWatsonMadrid 2LisaBlackSingapore 3LauraWilliamsSeattle 4MilanBrickSeoul Let’s see some examples of pattern matching in SQL. Example 1: Let’s display the first name, last name, and city of each customer whose city name starts with the letter 'S. Read more 1 Jan 0001 How to Trim Strings in SQL Problem: You’d like to remove specific characters from the beginning and end of a string. Example: Our database has a table named post with data in two columns: id and title. idtitle 1' News about dogs ' 3'Eurovision 2019 ' 4'New political climate' Let’s trim the title of each post to remove the unnecessary space at the beginning and end. Solution: We’ll use the TRIM function. Read more 1 Jan 0001 How to Sum Values of a Column in SQL? Problem: You’d like to sum the values of a column. Example: Our database has a table named game with data in the following columns: id, player, and score. idplayerscore 1John134 2Tom 146 3Lucy20 4Tom 118 5Tom 102 6Lucy90 7Lucy34 8John122 Let’s find the total score obtained by all players. Solution: SELECT SUM(score) as sum_score FROM game; Here’s the result: Read more 1 Jan 0001 How to Round Up a Number to the Nearest Integer in SQL Problem: You want to round up a number to the nearest integer. Example: Our database has a table named rent with data in the following columns: id, city, area, and bikes_for_rent. idcityareabikes_for_rent 1Los Angeles1302.151000 2Phoenix1340.69500 3Fargo126.44101 Let’s show each city’s name along with the ratio of its area to the number of bikes for rent. Read more 1 Jan 0001 How to Round Numbers in SQL Problem: You want to round a number to a specific number of decimal places. Example: Our database has a table named product with data in the following columns: id, name, and price_net. idnameprice_net 1bread2.34 2croissant1.22 3roll0.68 Suppose there’s a tax of 24% on each product, and you’d like to compute the gross price of each item (i.e., after taxes) and round the value to two decimal places. Read more 1 Jan 0001 How to Replace Part of a String in SQL Problem: You’d like to replace part of a string with another string. Example: Our database has a table named investor with data in the following columns: id, company, and phone. idcompanyphone 1Big Market123–300-400 3The Sunny Restaurant123–222-456 4My Bank123-345-400 We’d like to change the phone number format for each company by replacing the hyphen character with a space. Read more 1 Jan 0001 How to Order by Date in MySQL Problem: You want to sort the rows by date. Example 1: The exam table has two columns, subject and exam_date. subjectexam_date Mathematics2019-12-19 English2020-01-08 Science2020-01-05 Health2020-01-05 ArtNULL You want to sort the rows by exam_date. Solution: SELECT * FROM exam ORDER BY exam_date; The result looks like this (the rows are sorted in ascending order by exam_date): Read more 1 Jan 0001 How to Order by Count in SQL? Problem: You aggregated data into groups, but you want to sort the records in descending order by the number of elements in the groups. Example: Our database has a table named user with data in the following columns: id, first_name, last_name, and country. idfirst_namelast_namecountry 1LisaWilliamsEngland 2GaryAndersPoland 3TomWilliamsPoland 4MichaelBrownFrance 5SusanSmithUSA 6AnneJonesUSA 7EllieMillerPoland Let’s create a report on our users. Read more 1 Jan 0001 How to Order By Two Columns in SQL? Problem: You need to display records from a given table sorted by two columns. Example: Our database has a table named employee with the following columns: id, first_name, last_name, and salary. idfirst_namelast_namesalary 1LisaUlman3000 2AdaMuller2400 3ThomasGreen2400 4MichaelMuller3000 5MaryGreen2400 Let’s display all information for each employee but sort the records according to salary in descending order first and then by last name in ascending order. Read more 1 Jan 0001 How to Order Alphabetically in SQL Problem: You want to display records from a table in alphabetical or reverse-alphabetical order according to given column. Example: Our database has a table named customer. The customer table contains data in the id, first_name, and last_name columns. id first_name last_name 1 Susan Thomas 2 John Michael 3 Tom Muller Let’s display each customer’s information, sorted in ascending order by their last name. Read more 1 Jan 0001 How to Number Rows in SQL Problem: You would like to give each row in the result table a separate number. Example: Our database has a table named furniture with data in the following columns: code (primary key) and name. codename 101bed 202sofa 333chair 123bookcase 235table 766desk The furniture table stores the name of pieces of furniture that we want to number. Read more 1 Jan 0001 How to Multiply Two Columns in SQL Problem: want to multiply values from two columns of a table. Example: Our database has a table named purchase with data in the following columns: id, name, price, quantity, and discount_id. idnamepricequantitydiscount_id 1pen731 2notebook582 3rubber1131 4pencil case2423 Let’s multiply the price by the quantity of the products to find out how much you paid for each item in your order. Read more 1 Jan 0001 How to Join on Multiple Columns Problem: You want to join tables on multiple columns by using a primary compound key in one table and a foreign compound key in another. Example: Our database has three tables named student, enrollment, and payment. The student table has data in the following columns: id (primary key), first_name, and last_name. idfirst_namelast_name 1EllieWillson 2TomBrown 3SandraMiller The enrollment table has data in the following columns: primary key (student_id and course_code), is_active, and start_date. Read more 1 Jan 0001 How to Join Multiple (3+) Tables in One Statement Problem: You’d like to combine data from more than two tables using only one SELECT statement. Example: There are four tables in our database: student, teacher, subject, and learning. The student table contains data in the following columns: id, first_name, and last_name. idfirst_namelast_name 1TomMiller 2JohnSpring 3LisaWilliams 4EllieBarker 5JamesMoore The teacher table contains data in the following columns: id, first_name, last_name, and subject. Read more 1 Jan 0001 How to Group by Year in SQL Problem: You want to group your data by year. Example I: One of the columns in your data is transaction_date. It contains a date. You would like to group all your data by year and calculate the total money earned each year. The data table looks like this: transaction_datemoney 2018-03-251700 2019-09-12100 2018-07-141200 2018-01-05400 2019-06-082000 2020-03-061500 Solution 1 (displaying the year and the money earned): SELECT EXTRACT(year FROM transaction_date) AS year, SUM(money) AS money_earned FROM data GROUP BY EXTRACT(year FROM transaction_date); The result is: Read more 1 Jan 0001 How to Group by Two Columns in SQL Problem: You want to group your data by two columns so you can count some statistics. Example: In the order table, you have the columns order_date, product_id, customer_id, and number. You would like to count the number of products bought by each customer each day. The order table looks like this: order_dateproduct_idcustomer_idnumber 2020-11-25711 2020-11-251213 2020-11-265312 2020-11-26124 2020-11-26321 2020-11-261627 2020-11-26332 2020-11-27631 Solution: SELECT order_date, customer_id, SUM(number) AS products_number FROM order The result is: Read more 1 Jan 0001 How to Get the Year from a Datetime Column in MySQL Problem: You’d like to get the year from a date/datetime column in a MySQL database. Example: Our database has a table named conference with data in the columns id, name, and start_datetime. idnamestart_datetime 1Social Media World2019-02-20 14:15:34 2Mobile World 20172017-08-31 20:10:14 3Electronics Show2018-04-03 10:05:45 4Tech Asia 20192019-01-01 12:47:54 For each conference, let’s get its name and year. Read more 1 Jan 0001 How to Get the Month from a Date in MySQL Problem: You’d like to get the month from a date/datetime column in a MySQL database. Example: Our database has a table named apartment_rental with data in the columns id, address, floor, and start_date. idaddressfloorstart_date 1700 Oak Street22019-03-20 2295 Main Street32019-05-31 3506 State Road12019-01-03 43949 Route 3112019-02-01 For each available apartment, get the address, the floor, and the month when it’s available. Read more 1 Jan 0001 How to Get the Date from a Datetime Column in MySQL Problem: You’d like to get the date from a date and time column in a MySQL database. Example: Our database has a table named travel with data in the columns id, first_name, last_name, and timestamp_of_booking. idfirst_namelast_nametimestamp_of_booking 1LisaWatson2019-04-20 14:15:34 2TomSmith2019-03-31 20:10:14 3AndyMarkus2019-08-03 10:05:45 4AliceBrown2019-07-01 12:47:54 For each traveler, let’s get their first and last name and the booking date only. Read more 1 Jan 0001 How to Get the Current Date and Time in MySQL Problem: You’d like to get the current date and time for a MySQL database. Solution: We’ll use one of two functions, CURRENT_TIMESTAMP or NOW(), to get the current date and time. SELECT CURRENT_TIMESTAMP ; Here’s the result of the query: 2019-08-15 11:13:17 Discussion: The CURRENT_TIMESTAMP function in the MySQL database returns the current date and time (i.e. the time for the machine running that instance of MySQL). It is given as a value in the 'YYYY-MM-DD hh:mm:ss' format. Read more 1 Jan 0001 How to Get Yesterday’s Date in MySQL Problem: You would like to display yesterday's date (without time) in a MySQL database. Solution: SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY) AS yesterday_date; Assuming today is 2020-09-24, the result is: yesterday_date 2020-09-23 Discussion: To get yesterday's date, you need to subtract one day from today's date. Use CURDATE() to get today's date. In MySQL, you can subtract any date interval using the DATE_SUB() function. Read more 1 Jan 0001 How to Floor Numbers in SQL Problem: You want to round a number down to the nearest integer. Example: Our database has a table named employee with data in the following columns: id, first_name, last_name, and hours_worked (for the current month). idfirst_namelast_namehours_worked 1AlanWatson95 2LisaBlack225 3LauraWilliams104 Let’s show the first and last name of each employee along with the number of days they worked. Read more 1 Jan 0001 How to Find the Number of Days Between Two Dates in MySQL Problem: You’d like to get the difference, in days, between two dates in a MySQL database. Example: Our database has a table named food with data in the columns id, name, purchase_date, and expiration_date. idnamepurchase_dateexpiration_date 1bread 2019-07-202019-08-22 2butter2018-07-302019-08-10 3milk 2019-01-122019-01-13 4yogurt2019-02-252019-02-24 For each food product, let’s get the name of the product and the number of days between its expiration and purchase dates. Solution: We’ll use the DATEDIFF() function. Read more 1 Jan 0001 How to Find the Minimum Value of a Column in SQL Problem: You’d like to find the smallest numeric value in a column. Example: Our database has a table named employment with data in the following columns: id, first_name, last_name, department, and salary. idfirst_namelast_namedepartmentsalary 1EllieMartinesmarketing1200 2MartinJohnsonfinance2300 3MichaelJacobsproduction1100 4StephenKowalskimarketing4300 5StanleyMillermarketing3500 6JenyBrownfinance5000 7MargaretGreenmarketing1500 8LisaThomasproduction2800 Let’s find the lowest salary among all employees. Read more 1 Jan 0001 How to Find the Maximum Value of a Numeric Column in SQL Problem: You’d like to find the maximum value of a numeric column. Example: Our database has a table named product with data in the following columns: id, name, year, and items. idnameyearitems 1bread roll2018345 2chocolate2017123 3butter201934 4bread roll2019456 5butter201856 6butter201778 7chocolate201987 8chocolate201876 Let’s find the maximum number of items sold over all years. Read more 1 Jan 0001 How to Find the Last Day of the Month for a Given Date in MySQL Problem: You’d like to get the date of the last day of the month for a date in a MySQL database. Example: Our database has a table named car_sales with data in the columns id, make, model, and sale_date. idmakemodelsale_date 1FordKa2019-02-01 2ToyotaYaris2019-08-15 3OpelCorsa2019-06-22 For each car, let’s get the make and model and the last day of the month in which the car was sold. Read more 1 Jan 0001 How to Find the Average of a Numeric Column in SQL Problem: You’d like to calculate the average of numbers stored in a column. Example: Our database has a table named sale with data in the following columns: id, city, year, and amount. idcityyearamount 1Los Angeles20172345.50 2Chicago20181345.46 3Annandale2016900.56 4Annandale201723230.22 5Los Angeles201812456.20 6Chicago201789000.40 7Annandale201821005.77 8Chicago20162300.89 Let’s calculate the average sales, regardless of city or year. Read more 1 Jan 0001 How to Find Records with NULL in a Column Problem: You want to find records with NULL in a column. Example: Our database has a table named children with data in four columns: id, first_name, middle_name, and last_name. idfirst_namemiddle_namelast_name 1JohnCarlJackson 2TomNULLThomson 3LisaAliceNULL 4AnneNULLSmith Let’s find the id, first name, and last name of children without a middle name (NULL in column middle_name). We use the IS NULL operator for this. Solution: SELECT id, first_name, last_name FROM children WHERE middle_name IS NULL; Here’s the result: Read more 1 Jan 0001 How to Find Minimum Values in Columns Problem: You want to find rows that store the smallest numeric value in a column. Example: Our database has a table named weather with data in the following columns: id, city, and temperature. idcitytemperature 1Houston23 2Atlanta20 3Boston15 4Cleveland15 5Dallas34 6Austin28 Here’s how to find cities with the lowest temperature. Read more 1 Jan 0001 How to Find Maximum Values in Rows Problem: You want to find which rows store the largest numeric value in a given column. Example: Our database has a table named student with data in the following columns: id, first_name, last_name, and grade. idfirst_namelast_namegrade 1LisaJackson3 2GaryLarry5 3TomMichelin2 4MartinBarker2 5EllieBlack5 6MarySimpson4 Let’s find the students who have the highest grades. Read more 1 Jan 0001 How to Find Duplicate Rows in SQL? Problem: You have duplicate rows in your table, with only the IDs being unique. How do you find those duplicate entries? Example: Our database has a table named product with data in the following columns: id, name, and category. idnamecategory 1steakmeat 2cakesweets 3dsteakmeat 4porkmeat 5cakesweets 6cakesweets Let’s find duplicate names and categories of products. Read more 1 Jan 0001 How to Filter Rows without NULL in a column Problem: You want to find records without a NULL in a column. Example: Our database has a table named product with data in three columns: id, name, and price. idnameprice 1butterNULL 2milk2.35 3bread3.25 4cheeseNULL Let’s find the names and prices of products that have a price (without a NULL). Do this by using the IS NOT NULL operator. Read more 1 Jan 0001 How to Filter Records with Aggregate Function SUM Problem: You need to find rows in which groups have a sum of values in one column less than a given value. Example: Our database has a table named company with data in the following columns: id, department, first_name, last_name, and salary. iddepartmentfirst_namelast_namesalary 1marketingLoraBrown2300 2financeJohnJackson3200 3marketingMichaelThomson1270 4productionTonyMiller6500 5productionSallyGreen2500 6financeOlivierBlack3450 7productionJenifferMichelin2800 8marketingJeremyLorson3600 9marketingLouisSmith4200 Let’s find the names of departments that have sums of salaries of its employees less than 7000. Read more 1 Jan 0001 How to Filter Records with Aggregate Function COUNT Problem: You want to find groups of rows with a specific number of entries in a group. Example: Our database has a table named product with data in the following columns: id, name and category. idnamecategory 1sofafurniture 2glovesclothing 3T-Shirtclothing 4chairfurniture 5deskfurniture 6watchelectronics 7armchairfurniture 8skirtclothing 9radio receiverelectronics Let’s find the category of products with more than two entries. Read more 1 Jan 0001 How to Filter Records with Aggregate Function AVG Problem: You want to find groups of rows in which the average of values in a column is higher or lower than a given value. Example: Our database has a table named product with data in the following columns: id, name, grocery and price. idnamegroceryprice 1milkGreen Shop2.34 2breadClark’s Grocery3.56 3breadSuper Market4.15 4milkSuper Market1.80 5breadGrocery Amanda2.26 6milkViolet Grocery3. Read more 1 Jan 0001 How to Eliminate Duplicate Rows in SQL Problem: You’d like to eliminate any duplicate rows from the result set of a query so that each row appears only once. Example: Our database has a table named clothes with data in the following columns: id, name, color, and year_produced. idnamecoloryear_produced 1T-shirtyellow2015 2jacketblue2016 3jeansblack2015 4jacketblue2015 5jacketgreen2016 6jacketyellow2017 7hatyellow2017 Let’s get the non-repeated names and colors of clothes produced before 2017. Read more 1 Jan 0001 How to Delete a Foreign Key Constraint in SQL Problem: You want to drop a foreign key from a table in a database. Example: We want to remove the foreign key named fk_student_city_id from the table student. Solution 1 (new table): ALTER TABLE student DROP CONSTRAINT fk_student_city_id; Discussion: To drop a foreign key from a table, use the ALTER TABLE clause with the name of the table (in our example, student) followed by the clause DROP CONSTRAINT with the name of the foreign key constraint. Read more 1 Jan 0001 How to Create a Table with a Foreign Key in SQL Problem: You want to create a foreign key for a table in a database. Example: We would like to create a table named student that contains a foreign key that refers to the id column in the table city. Solution 1 (new table): CREATE TABLE student ( id INT PRIMARY KEY, first_name VARCHAR(100) NOT NULL, last_name VARCHAR(100) NOT NULL, city_id INT FOREIGN KEY REFERENCES city(id) ); Discussion: To create a new table containing a foreign key column that references another table, use the keyword FOREIGN KEY REFERENCES at the end of the definition of that column. Read more 1 Jan 0001 How to Count the Number of Rows in a Table in SQL Problem: You’d like to determine how many rows a table has. Example: Our database has a table named pet with data in the following columns: id, eID (electronic identifier), and name. ideIDname 123456sparky 223457mily 3NULLlessy 4NULLcarl 534545maggy Let’s count all rows in the table. Solution: COUNT(*) counts the total number of rows in the table: Read more 1 Jan 0001 How to Count Distinct Values in SQL Problem: You’d like to count how many different non-NULL values there are in a given column. Example: Our database has a table named customer with data in the following columns: id, first_name, last_name, and city. idfirst_namelast_namecity 1JohnWilliamsChicago 2TomBrownAustin 3LucyMillerChicago 4EllieSmithDallas 5BrianJonesAustin 6AllanDavisNULL Let’s find the number of different (and non-NULL) cities. Read more 1 Jan 0001 How to Convert a String to Uppercase in SQL Problem: You would like to convert a string to uppercase. Example: Our database has a table named questionnaire with data in the following columns: id, first_name, last_name, and favorite_car. idfirst_namelast_namefavorite_car 1AlanJacksonHonda Civic 2ElisaThomsonTOYOTA Camry 3MaryMartinesNissan rogue 4ChrisBrownford focus 5AdamSpringRam PICKUP Our table stores the make and model of the favorite car for each person who filled out our questionnaire. Read more 1 Jan 0001 How to Convert a String to Lowercase in SQL Problem: You would like to convert a string to lowercase. Example: Our database has a table named product with data in the id and name columns. idname 1Cobb Salad 2Pot roast 3Jerky 4BANANA SPLIT 5CORN bread 6chicken fried Steak Notice that the naming styles are inconsistent for these products. Read more 1 Jan 0001 How to Concatenate Strings in SQL Problem: You want to join strings from two columns of a table into one. Example: Our database has a table named student with data in the following columns: id, first_name and last_name. idfirst_namelast_name 1LoraSmith 2EmilBrown 3AlexJackson 4MartinDavis Let’s append the first name to the last name of the student in one string. Use a space between each name. Read more 1 Jan 0001 How to Change Seconds to a Time Value in MySQL Problem: You’d like to display a number of seconds as a time value in hours, minutes, and seconds in MySQL. Example: Our database has a table named athlete_score with data in the columns id, first_name, last_name, and score_seconds. idfirst_namelast_namescore_seconds 1EmilyWatson1124 2TomGarcia987 3GaryMartinez1003 4JamesAnderson1233 For each athlete, let’s get their first and last names and their record time from the seconds_record column. Read more 1 Jan 0001 How to Change Datetime Formats in MySQL Problem: You’d like to change the format of date and time data in a MySQL database. Example: Our database has a table named student_platform with data in the columns id, first_name, last_name, and registration_datetime. idfirst_namelast_nameregistration_datetime 1LoraLorens2019-02-23 12:04:23 2AnneSmith2018-07-10 10:12:15 3TomJackson2019-03-09 08:20:33 4RichardWilliams2018-09-30 06:07:34 For each student, let’s get their first name, last name, and registration date and time. Read more 1 Jan 0001 How to Calculate the Difference Between Two Timestamps in MySQL Problem: You have two columns of the type timestamp and you want to calculate the difference between them. Example: In the travel table, there are three columns: id, departure, and arrival. You'd like to calculate the difference between the arrival and the departure. The travel table looks like this: iddeparturearrival 12018-03-25 12:00:002018-04-05 07:30:00 22019-09-12 15:50:002019-10-23 10:30:30 32018-07-14 16:15:002018-07-14 20:40:30 42018-01-05 08:35:002019-01-08 14:00:00 Solution 1 (difference in days, hours, minutes, or seconds): SELECT id, departure, arrival, TIMESTAMPDIFF(SECOND, departure, arrival) AS difference FROM travel; The result is: Read more 1 Jan 0001 How to Calculate the Difference Between Two Dates in MySQL Problem: You have two columns of the date type and you want to calculate the difference between them. Example: In the travel table, there are three columns: id, departure, and arrival. You'd like to calculate the difference between arrival and departure, or the number of days from arrival to departure inclusively. The travel table looks like this: iddeparturearrival 12018-03-252018-04-05 22019-09-122019-09-23 32018-07-142018-07-14 42018-01-052018-01-08 Solution: SELECT id, departure, arrival, DATEDIFF(arrival, departure) AS date_difference, DATEDIFF(arrival, departure) + 1 AS days_inclusive FROM travel; The result is: Read more 1 Jan 0001 How to Calculate a Square Root in SQL Problem: You want to find the square root of a number. Example: You want to compute the square root of all numbers in the column number from the table data. number 9 2 1 0.25 0 -4 Solution 1: SELECT number, SQRT(number) AS square_root FROM data; The result is: Read more 1 Jan 0001 How to Add Time to a Datetime Value in MySQL Problem: You’d like to add a certain amount of time to a datetime value in a MySQL database. Example: Our database has a table named flight_schedule with data in the columns flight, aircraft, and arrival_datetime. flightaircraftarrival_datetime EK10L12012019-04-20 15:15:00 AY12K20012019-03-31 20:10:00 LA105F2052019-08-03 11:15:00 LH30K2562019-07-01 12:47:00 For each flight, let’s get the flight code, aircraft code, and a new arrival date and time. Read more 1 Jan 0001 How to Add Ranking Positions to Rows with DENSE_RANK() in SQL Problem: You want to add a ranking position to rows consecutively, even if the rows have the same values. Example: Our database has a table named competition with data in the following columns: id (primary key), first_name, last_name, and score. idfirst_namelast_namescore 11JohnThomas345 14MaryJohnson222 16LisaBrown154 23AlanBlake222 32ChrisTaylor154 Let’s display all details about students: their last name, first name, and scores sorted by score in descending order. Read more 1 Jan 0001 How to Add Ranking Positions of Rows in SQL with RANK() Problem: You want to rank records by skipping ranking positions after rows that have the same rank. Example: Our database has a table named championship with data in the following columns: id (primary key), user_name, and score. iduser_namescore 111John12 112Mary23 115Lisa45 120Alan23 221Chris23 Let’s display all users’ names and their scores sorted in descending order and ranked by score. Read more 1 Jan 0001 How to Add Days to a Date in MySQL Problem: You’d like to add days to a date in a MySQL database. Example: Our database has a table named trip with data in the columns id, city, and start_date. idcitystart_date 1Chicago2019-06-22 2Houston2019-07-15 3Dallas2019-08-30 4Austin2019-09-23 Let’s add two days to the start dates and get the trip cities with the new start dates. Read more