Count the records of a query - mysql

All I need to do is to count all records that match this query... that is the only info I need.. is the count of the records... what is the most efficient way to do that?
SELECT id, country, city
FROM sales
WHERE country='Germany'
AND city='Munich'
AND closed<>0
I mean, I assume this is correct but is there a more efficient way to do this? I will be running this counting query often...
SELECT COUNT(*)
FROM sales
WHERE country='Germany'
AND city='Munich'
AND closed<>0
Should I use * or something more specific?

If you need to count the Null value also for your record count then use count(*) or if ignore the Null value to be counted then use count().
DECLARE #AA AS TABLE (ID INT, NAME VARCHAR(10))
INSERT INTO #AA VALUES(1,NULL)
INSERT INTO #AA VALUES(2,'A')
INSERT INTO #AA VALUES(3,'B')
INSERT INTO #AA VALUES(4,'C')
SELECT * FROM #AA
SELECT COUNT(*) FROM #AA
SELECT COUNT(NAME) FROM #AA
As you execute the above query you can find that there will be four records in #AA table but if you use COUNT(*) if will result 4 and if you use COUNT(NAME) it will result 3 this example is for SQL Server, but the mysql will do same.

Please refer the following link.
MySQL: Fastest way to count number of rows
Hope this helps you.

Related

how to copy only distinct values from one table to another in Mysql?

I have a MySql database round-about 2.5GB,
The table[A] has following columns, |anoid| |query| |date| |item-rank| |url|
I have just created another table[b] having columns only |query| and |date|
I want to insert all the distinct records in query column, with it's respective date, from Table[A] to [B], is there any fast query?
Use INSERT INTO ... SELECT:
INSERT INTO Tableb(query, date)
SELECT query, MAX(Date) AS MAXDate
FROM Tablea
GROUP BY query
This will give you distinct query with the most recent date.
You can use
insert into table[b](query,date)
select query,date from table[a] order by table[a] asc
INSERT INTO tableB
SELECT * FROM tableA
group by query
Note: please remove id from both the tables while applying the above query.

Count number of records with duplicates

My subreport goes through a list of ID's. Each ID has a location assigned to it. The report is grouped by the location (Group #1), then by ID (Group #2).
In the table, the ID's should look like:
14600
14602
14602
14602
14700
14703
14704
14704
My desired output would be 2 because there are 2 ID's with more than one entry. How can I easily calculate this?
You can try this:
DECLARE #temp table(num integer);
INSERT INTO #temp(num) VALUES (14600), (14602), (14602), (14602), (14700), (14703), (14704), (14704);
SELECT COUNT(distinct num) repeats
FROM
(SELECT
num, count(num) as counts
FROM #temp
GROUP BY num
HAVING COUNT(num) > 1) a;
Sounds like you're looking for a combination of COUNT and DISTINCT, in conjunction with ensuring that there is more than one occurrence. You can accomplish this with something like:
SELECT COUNT(DISTINCT id) FROM table_name HAVING COUNT(*) > 1
This returns the number of distinct IDs in the table. In your case, this is 2.

MYSQL Save Query Results into Another Table

I'm looking to store the results of a query that returns a list of all the unique values in a particular column, and how many times they are repeated:
SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name;
This returns something like:
col_name
recordA
recordB
recordC
recordD
recordE...
total
39
91817
982027
211872
256...
It's working great and exactly what I need. But I need to store the results into another table (eg. countTable) so I don't have to do the query every time, can index it... etc.
Let's say countTable has the exact same structure as the results here. Two columns: name and count of the same types as the original result.
This is going to probably raise some laughs, but currently I feel like this is close:
INSERT INTO countTable (name, count) SELECT col_name, total FROM
(SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name);
But I get an error: ERROR 1248 (42000): Every derived table must have its own alias
I have no idea how to wrap this query right, or if I'm supposed to use another AS somewhere?
Any help greatly appreciated!!
Thanks
You can do a SELECT right after the INSERT statement. As long as what you are selecting matches the values you want to insert (in this case name and count). You can test what will be inserted into your countTable by just running the select statement by itself.
INSERT INTO countTable (name, count)
SELECT col_name, COUNT(*) AS 'total'
FROM dataTable
GROUP BY col_name;
AH! Turns out I was very close in my original query:
INSERT INTO countTable (name, count) SELECT col_name, total FROM
(SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name);
I DID need to add an extra AS at the very end. Every derived table MUST indeed have its own alias :)
INSERT INTO countTable (name, count) SELECT col_name, total FROM
(SELECT col_name, COUNT(*) AS 'total' FROM dataTable GROUP BY col_name) AS count;
But it would seem I'm wrapping it unnecessarily as evidenced by spaceman's answer.

SQL query / number of records

I have a simple table with two columns. The first field represents an id, the second one a name (string value). No field is unique. So, e.g., there are many records like:
What I need is a simple SQL statement which shows me the whole table in the following format and inserts the content into a new table.
Any help?
You have to use group by:
insert into tab2 (name,cnt)
select name, count(1) as cnt
from tab
group by name
Here is more informations about aggregate functions.
SQL Fiddle DEMO
Just use COUNT function to count from_id. And if you want to count in group, use GROUP BY clause for that. Like this one.
SELECT `name`, COUNT(from_id) AS `COUNT`
FROM myTable
GROUP BY `name`;
This will return your desired result.
Now you want to insert it into new table then you can do like this:
INSERT INTO newTable (`name`, `count`)
SELECT `name`, COUNT(from_id) AS `COUNT`
FROM myTable
GROUP BY `name`;

How to get the max value of a field without grouping in MySql

I have a query with many wheres and orders criterias. One of the fields of the select is 'price' (element price) but I would like to have also (in every row) the maximun price of all the selected elements.
I tried to include MAX aggregate function on select hoping that this will return desired value, but insetead of that, price and MAX(price) returns the same. Searching into MySql doc I found the reason:
If you use a group function in a
statement containing no GROUP BY
clause, it is equivalent to grouping
on all rows.
Is there a way to solve this problem?
Thanks in advance!
There's a similar question (but not resolving this): find max value without aggregate operator in mysql
You can do this:
SELECT
id,
price,
(SELECT MAX(price) FROM your_table) AS max_price
FROM your_table
I'm not sure why you'd want to return that value on every row though... I'd probably do this in two separate queries, or else use a UNION ALL:
SELECT id, price FROM your_table
UNION ALL
SELECT NULL, MAX(price) FROM your_table
Maybe you could use a stored procedure like so:
CREATE PROCEDURE QueryWithMax ([parameter list if necessary])
BEGIN
-- Obtain the maximum price
DECLARE x INT UNSIGNED; -- change datatype if appropriate
SET x = SELECT
MAX(price)
FROM
...
WHERE
...
;
-- Now do your query
SELECT
price,
[other columns],
x AS MaxPrice
FROM
...
WHERE
...
GROUP BY
...
;
END
I haven't tried this, but if you had a subquery that extracts the maximum price (so you get one row), and then do a cross join (cartesian product) with it. You should get something like what you want. I can't vouch for how fast this would be.