Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Tuesday, April 7, 2020

MySQL Subqueries

For most of my software development career, I used an Oracle database. At my current job, we use a MySQL database. So I am still learning the ins and outs of MySQL. Here is a common thing I would do in Oracle:
SELECT
  name, total_points
FROM (
  SELECT
    name,
    SUM(points) AS total_points
  FROM
    scores
  GROUP BY
    name
)
WHERE
  total_points >  10
ORDER BY
  total_points DESC, name
That would give me a list of all players who have scored more than 10 points. When I tried this same format in MySQL, I got this error:
Error Code: 1248. Every derived table must have its own alias
After a little searching, I came up with the solution. I had to name my inner query. So with a slight modification it worked:
SELECT
  tp.name, tp.total_points
FROM (
  SELECT
    name,
    SUM(points) AS total_points
  FROM
    scores
  GROUP BY
    name
) tp
WHERE
  total_points >  10
ORDER BY
  total_points DESC, name


Tuesday, October 29, 2013

Oracle Equivalent of MySQL's LIMIT (Or how to page results in Oracle)

I'm really just posting this for my own benefit but if you're reading this and it has been helpful, drop me a comment to let me know.
SELECT
  *
FROM (
  SELECT 
    a.*,
    ROW_NUMBER() OVER (ORDER BY column_to_sort) rn
  FROM
    my_table a
  WHERE
    my_column_to_filter = 'my_value_to_filter'
 )
WHERE
  rn >= my_starting_row AND rn <= my_ending_row
 
Blogger Templates