Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have 2 tables
Course ( ID Date Description Duration Meatier\_ID Promotion\_ID).
second table
Ensign( E\_Id Meatier\_Id Promotion\_Id)
infarct i have an id based on that id i have to Select data from Ensign where id=Eng\_Id then i need to select data from Course where Meatier\_Id and Promotion\_Id in table Course ... | Join the two tables together on Meater\_ID and Promotion\_ID. Then select those rows where Eng\_Id is the id you are working with.
```
SELECT *
FROM Course c
INNER JOIN Ensign e
ON e.Meatier_ID = c.Meatier_ID
AND e.Promotion_ID = c.Promotion_ID
WHERE e.Eng_Id = <id value here>
```
EDIT:
The above should work fo... | Your question is bit vague, But I gave it a try
```
--These two variables take the place for your 'Earlier Query' values
DECLARE @Meatier_ID INT = 100,
@Promotion_Id INT = 15
--The query
SELECT *
FROM Course AS C
INNER JOIN Ensign AS E ON C.ID = E.E_Id
WHERE C.Meatier_ID = @Meatier_ID
AND C.Promotion_Id = @Pr... | Selecting data from two tables with sql query | [
"",
"sql",
"database",
"sql-server-2008",
""
] |
I'm looking for a lighweight database/SQL-server to run on a Raspberry Pi. Since it should be accessible from more than one application, embedded databases like SQLite would not work, thus it should be a standalone database (I know that SQLite databases can be read by more than one process at the same time, but I'm mos... | Look into this <http://www.firebirdsql.org/>. It should be lightweight. | You're just speculating based on anecdotes, which is the worst way to make decisions.
Build a test case on a Pi, exercise it and collect metrics. You may find that the flash storage of the Pi is sufficiently fast that the write locks aren't a big deal. | Lightweight SQL server for Raspberry Pi | [
"",
"mysql",
"sql",
"sql-server",
"sqlite",
"raspberry-pi",
""
] |
Can any one help me in getting the last 12 months names from the current date (month).
I want this query in slq server. | Requires sql-server 2008
```
select datename(m,dateadd(m,-a,current_timestamp)) monthname,
datepart(m,dateadd(m,-a,current_timestamp)) id
from (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) x(a)
```
Result:
```
monthname id
December 12
November 11
October 10
September 9
August 8
Ju... | You can use common table expression for your solution:
```
;WITH DateRange AS(
SELECT GETDATE() Months
UNION ALL
SELECT DATEADD(mm, -1, Months)
FROM DateRange
WHERE Months > DATEADD(mm, -11, GETDATE())
)
SELECT DateName(m, Months) AS Months, Month(Months) AS ID FROM DateRange
```
shows previou... | Get Previous 12 months name/id from current month | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I just had to scour the internet for this code yet again so I figured I would put it here so I can find it a little faster the next time and hopefully you found it a little faster too :) | Check this.
The code below can check digit in all GTIN's (EAN8, EAN13, EAN14, UPC/A, UPC/E)
```
CREATE FUNCTION [dbo].[check_digit]
(
@GTIN VARCHAR(14)
)
RETURNS TINYINT
AS
BEGIN
DECLARE @Index TINYINT,
@Multiplier TINYINT,
@Sum TINYINT,
@checksum TINYINT,
@resul... | ```
CREATE FUNCTION [dbo].[fn_EAN13CheckDigit] (@Barcode nvarchar(12))
RETURNS nvarchar(13)
AS
BEGIN
DECLARE @SUM int , @COUNTER int, @RETURN varchar(13), @Val1 int, @Val2 int
SET @COUNTER = 1 SET @SUM = 0
WHILE @Counter < 13
BEGIN
SET @VAL1 = SUBSTRING(@Barcode,@counter,1) * 1
... | SQL proc to calculate check digit for 7 and 12 digit upc | [
"",
"sql",
"t-sql",
"barcode",
"checksum",
""
] |
I am trying to select products that are found in an range of categories and the product was created within the last 4 months. I have done this with this
```
select DISTINCT category_skus.sku, products.created_date from category_skus
LEFT JOIN products on category_skus.sku = products.sku
WHERE category_code > ‘706... | Would
```
where category_code in (select category_code from category_skus where (category_code between '70699' and '70791') or (category_code in ('60130','60420')))
and products.created_date > ...
```
work? Not sure if I understood the question correctly. | Your conditions are a bit mixed up. There won't be any products between 70699-70791 that also = 60130. Try nesting your category\_code conditions in their own AND statement:
```
SELECT DISTINCT category_skus.sku, products.created_date
FROM category_skus
LEFT JOIN products ON category_skus.sku = products.sku
WHERE pr... | mysql - selecting multiple ranges from the same table column | [
"",
"mysql",
"sql",
"range",
"between",
""
] |
Is there a way to run a query for a specified amount of time, say the last 5 months, and to be able to return how many records were created each month? Here's what my table looks like:
```
SELECT rID, dateOn FROM claims
``` | ```
SELECT COUNT(rID) AS ClaimsPerMonth,
MONTH(dateOn) AS inMonth,
YEAR(dateOn) AS inYear FROM claims
WHERE dateOn >= DATEADD(month, -5, GETDATE())
GROUP BY MONTH(dateOn), YEAR(dateOn)
ORDER BY inYear, inMonth
```
In this query the `WHERE dateOn >= DATEADD(month, -5, GETDATE())` ensures that it's for the past ... | Unlike the other two answers, this will return all 5 months, even when the count is 0. It will also use an index on the onDate column, if a suitable one exists (the other two answers so far are non-sargeable).
```
DECLARE @nMonths INT = 5;
;WITH m(m) AS
(
SELECT TOP (@nMonths) DATEADD(MONTH, DATEDIFF(MONTH, 0, GET... | How to count number of records per month over a time period | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I'm using Azure to host my database. The most common solutions to this problem I've found all have to do with incorrect data in the SQL query. I'm using parameters so I wouldn't think that would be an issue. My input data doesn't include any characters that SQL would recognize for a query. I'm stumped. Here is my code.... | I think your mistake in insert statement.
Where table name `campMeritBadgeRecords` and `values` are combined in insert statement so you have to add extra space after table name `campMeritBadgeRecords`
So your statement will be like that
```
Dim insertCMD As New SqlCommand("INSERT INTO campMeritBadgeRecords values" ... | My guess would be this line...
```
INSERT INTO campMeritBadgeRecords" + _
"VALUES (@recordID," + _
```
You aren't leaving a space between campMeritBadgeRecords and VALUES, so SQL Server reads it as
```
INSERT INTO campMeritBadgeRecordsVALUES(
``` | SQL Incorrect syntax near "," when using parameterized SQL | [
"",
"sql",
"vb.net",
"azure",
""
] |
I want the value for users with the right ref and also users with extra value 1.
I have the following query but its not giving unique rows ,its giving duplicate rows.How do I resolve that ? I really appreciate any help.
basically its repeating values of ref.id if tab2.user=1 which repeats 4,6 row again in the final ... | After your last comment:
```
SELECT sno, users, tab1.ref, extra, max(ad) as ad
FROM
tab1,tab2
WHERE tab1.ref=tab2.ref
AND tab1.users = 1
OR tab1.extra=1
group by sno, users, ref, extra;
```
This will max the ad column (alternatively you can use min - all depends on your requirements)
example: <http... | You will probably need to use join
```
SELECT * FROM
tab1 LEFT JOIN tab2 ON tab1.ref=tab2.ref
WHERE tab1.users = 1 OR tab1.extra=1;
GROUP BY tab1.users
```
edit: added group by | sql query has few rows which are duplicate | [
"",
"mysql",
"sql",
""
] |
Noob SSIS question please. I am working on a simple database conversion script. The original data source have the phone number saved as a string with len = 50 in a column called Phone1. The destination table has the telephone number saved as a string with len = 20 in a column called Telephone. I keep getting this warni... | Your conversion should result in a NEW variable, do not use Phone1. Use the name of the Converted value. | **Root cause** - This warning message appears over the SSIS data flow task when the datatype length of the source column is more than the datatype length of the destination column.
**Resolution** - In order to remove this warning message from SSIS solution, make sure datatype length of the source column should be equa... | SSIS Truncate Warning when moving data from a string max length 50 to a string max length 20 | [
"",
"sql",
"sql-server",
"ssis",
""
] |
i have the following row in my database:
```
'1', '1', '1', 'Hello world', 'Hello', '2014-01-14 17:33:34'
```
Now i wish to select this row and get only the date from this timestamp:
i have tried the following:
```
SELECT title, FROM_UNIXTIME(timestamp,'%Y %D %M') AS MYDATE FROM Team_Note TN WHERE id = 1
```
I h... | Did you try this?
```
SELECT title, date(timestamp) AS MYDATE
FROM Team_Note TN
WHERE id = 1
``` | You need to use DATE function for that:
<http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date>
```
SELECT title,
DATE(timestamp) AS MYDATE
FROM Team_Note TN
WHERE id = 1
``` | Select date from timestamp SQL | [
"",
"mysql",
"sql",
""
] |
Wondering how can I get data for any year and its prior year's when a year is given in where clause. Example: If i give 2012 as year in where clause, I should get both 2012 and 2011's data. This is in SQL Server 2008.
```
Select * from TableA where Year = 2012
```
but i want for 2011 in the same query.
Thank you! | You can use [`IN`](http://technet.microsoft.com/en-us/library/ms177682.aspx), which allows you to define a list:
```
Select * from TableA where Year IN (2011, 2012);
``` | If you only want to put the constant year in once, you could do this:
```
Select *
from TableA
where 2012 in (Year, Year + 1)
``` | Sql query for a particular year and the previous year's data | [
"",
"sql",
"sql-server-2008",
""
] |
I'm looking for a way to count how many results have been omitted by my sql query (i'm working with Sqlite) :
```
SELECT id FROM users GROUP BY x, y, email;
```
This query return me 121 id (of 50 000), it would be nice to know how many id have been omitted for each couple of (x,y).
Is it possible ?
Thank for your h... | ```
SELECT id, COUNT(*) -1 AS omitted FROM users GROUP BY x, y, email;
```
...assuming you actually want "to know how many have been omitted for each tuple `(x, y, email)`. | You can try this:
```
SELECT COUNT(*)
FROM
(
SELECT *
FROM users
MINUS
SELECT id
FROM users
);
```
This shows you all of the records minus the ones you selected. Hope this helps. | SQL - Count the number of omitted results | [
"",
"sql",
"sqlite",
"count",
""
] |
I have one master table in SQL Server 2012 with many fields.
I have been given an excel spreadhseet with new data to incorporate, so I have in the first instance, imported this into a new table in the SQL database.
The new table has only two columns 'ID', and 'Source'.
The ID in the new table matches the 'ID' from t... | ```
UPDATE
MainTable
SET
MainTable.Source = NewTable.Source
FROM
MainTable
INNER JOIN
NewTable
ON
MainTable.ID = NewTable .ID
```
That should do the trick | You could do
```
UPDATE MainTable
SET MainTable.Source = NewTable.Source
FROM NewTable
WHERE MainTable.ID = NewTable .ID
``` | Combining Values from SQL Table into a Second Table | [
"",
"sql",
""
] |
`hive` rejects this code:
```
select a, b, a+b as c
from t
where c > 0
```
saying `Invalid table alias or column reference 'c'`.
do I really need to write something like
```
select * from
(select a, b, a+b as c
from t)
where c > 0
```
EDIT:
1. the computation of `c` it complex enough for me not to want to repea... | Use a Common Table Expression if you want to use derived columns.
```
with x as
(
select a, b, a+b as c
from t
)
select * from x where c >0
``` | You can run this query like this or with a Common Table Expression
```
select a, b, a+b as c
from t
where a+b > 0
```
Reference the below order of operations for logical query processing to know if you can use derived columns in another clause.
Keyed-In Order
1. SELECT
2. FROM
3. WHERE
4. GROUP BY
5. HAVING
6. ORDE... | Using new columns in the "where" clause | [
"",
"sql",
"hive",
""
] |
Have CTE like :
```
WITH fnl as
(select lo.id , s.service_name , lo.obj_name ,
........
from dbo.r_objects ro
inner join dbo.services s on ro.service_id = s.id
inner join dbo.local_objects lo on ro.local_object_id = lo.id
where ro.service_id = @service_id
)
select id , service_name , CAST... | ```
select lo.id , s.service_name , lo.obj_name ,
........
INTO #temp
from dbo.r_objects ro
inner join dbo.services s on ro.service_id = s.id
inner join dbo.local_objects lo on ro.local_object_id = lo.id
where ro.service_id = @service_id
IF EXISTS (SELECT 1 FROM #temp)
begin
select id , s... | I don't think CTE is appropriate use for the query that you have. I would be much better to do something like this. Instead of your CTE just place what you have inside that sub select. Later you can continue checking your vairable.
```
DECLARE @table_count INT
SELECT @table_count = COUNT(*)
FROM ( SELECT somestuff
... | How to check WITH statement is empty or not | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I'm trying to see if it's possible to efficiently select a period a given date belongs to.
Let's say I have a table
```
id<long>|period_start<date>|period_end<date>|period_number<int>
```
and lets say I want for every id the period that "2013-11-20" belongs to.
i.e. naively
```
select id, period_number
from per... | Why aren't you creating "boundary periods"?
Choose arbitrary beginning\_of\_time and end\_of\_time dates e.g. 01/01/0001 and 31/12/9999 and insert a fake period. Your example period\_table will become:
```
+--+------------+----------+-------------+
|id|period_start|period_end|period_number|
+--+------------+----------... | Note: I missed the database engine you were using, so I answered from the perspective of SQL Server. However, the query is pretty simple and you should be able to adapt it to your own needs.
The best I can come up with is, if your table is clustered (or at least indexed) on `FromDate`, a query that works in 2 seeks:
... | Selecting an appropriate period or max/minimum period when outside of the period set | [
"",
"sql",
"ingres",
""
] |
For the first time in my professional career I found the need of join the result of a join with a table being the first join an inner join and the second a left outer join.
I came to this solution:
```
SELECT * FROM
(
TableA INNER JOIN TableB ON
TableA.foreign = TableB.id
)
LEFT OUTER JOIN TableC
ON TableC.id... | Yes it is correct, but it does nothing different than the same (simpler) query without the parentheses:
```
SELECT *
FROM TableA
INNER JOIN TableB
ON TableA.foreign = TableB.id
LEFT OUTER JOIN TableC
ON TableC.id = TableB.id;
```
**[SQL Fiddle showing both queries with t... | You should do it in a simpler way.
```
SELECT * FROM
TableA
INNER JOIN TableB ON TableA.foreign = TableB.id
LEFT OUTER JOIN TableC ON TableB.id = TableC.id
```
Usually it is done that way. | Outer left join of inner join and regular table | [
"",
"mysql",
"sql",
"join",
"left-join",
""
] |
I am new to SQl and try to learn on my own.
i am learn the usage of if and else statement in SQL
Here is the data where I am trying to use, if or else statement
in the below table, i wish to have the comments updated based on the age using the sql query, let say if the age is between 22 and 25, comments" under gradua... | # [How To Use Case](http://technet.microsoft.com/en-us/library/ms181765.aspx)
Try with CASE Statement
```
Select personid,lastname,firstname,age,
Case when age between 26 and 27 then 'post graduate'
when age between 28 and 30 then 'working and single'
when age between 31 and 33 then ' ... | As by your requirement, we can't use if...else statement. Case..when statement will be most suitable one. And another one thing We can't able to use if...else inside of any queries(I mean inside of select, insert, update).
And your
```
Select personid,lastname,firstname,age,
Case when age between 26 and 27 then 'p... | SQL, Multiple if statements, then, or else? | [
"",
"sql",
""
] |
I'm trying to count all the items for each brand and concatenate the brand name + number of items.
I have this query in SQL Server 2008 R2:
```
SELECT DISTINCT
Brands.BrandName + ' ' + COUNT(Items.ITEMNO) as ITEMSNO,
Brands.BrandId
FROM Items, Brand_Products, Brands
WHERE
Items.ITEMNO=Brand_Products.... | This will work, fist you count items based on BrandId in CTE and than join it with Brand table.
```
WITH ItemCount
AS ( SELECT BrandId
,COUNT(Items.ITEMNO) AS item_Count
FROM Items
,Brand_Products
,Brands
WHERE Items.ITEMNO = Brand_Products.... | Retrieve the field you're looking for twice, once in the concatenated field answer, and once by itself. This should solve your issue with DISTINCT. | Concatenate nvarchar and int while maintaining Distinct result | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have an Oracle table which has a column called `sql_query`. All the SQL queries are placed in this column for all the records in that table.
Now, I see many records which have NO SPACE before WHERE in WHERE clause. I need it because the field hits several web forms and I get a syntax error.
Ex:
```
Select * from h... | An easy way is to just use the `like` operation, assuming that your SQL queries are all simple (such as having a single `where` clause):
```
select *
from table t
where sql_query like '%where %' and sql_query not like '% where %';
```
You can readily turn this into an update:
```
update table
set sql_query = rep... | This query will look for any instances of the column that don't have the word 'WHERE' with a space before it. Then, if the word WHERE exists in those records, it will update it to '(space) WHERE'
```
UPDATE Table
SET SqlQuery = REPLACE(SqlQuery, 'WHERE', ' WHERE')
WHERE SqlQuery NOT LIKE '% WHERE%'
``` | Oracle SQL String search with no spaces and replace with space | [
"",
"sql",
"oracle-sqldeveloper",
""
] |
I have a table of products and each record has the price it was sold at, which can vary
```
+-------+-----+----+
|Product|Price|Date|
+-------+-----+----+
|a |2 |A |
+-------+-----+----+
|a |3 |B |
+-------+-----+----+
|a |4 |C |
+-------+-----+----+
|a |1 |D |
+-------+-----+--... | You could always use an CTE if this is on SQL server.
```
WITH CTE AS
(
SELECT Product, MAX(Price) AS Price
FROM TableName
GROUP BY Product
)
SELECT CTE.Product, CTE.Price, T.Date
FROM CTE
INNER JOIN
TableName T ON CTE.Product = T.Product AND CTE.Price = T.Price
```
However, there could be other viable options that a... | Try this-
```
SELECT
PRODUCT
,PRICE
,DATE
FROM
( SELECT
PRODUCT
,PRICE
, DATE
, RANK() OVER (PARTITION BY PRODUCT ORDER BY PRICE DESC) AS RANKED_PRICE
FROM TableName
) RANKED_DATA
WHERE RANKED_PRICE IN (1,2,3....N)
```
What we are doing is ranking the rows partitioned b... | How to query a specified row from each group | [
"",
"sql",
"sql-server",
"group-by",
"row",
""
] |
For Example:
**Table:** test
```
+--+-----+-----+
|id|name |value|
+--+-----+-----+
|1 |test1|5 |
+--+-----+-----+
|2 |test2|3 |
+--+-----+-----+
|3 |test3|7 |
+--+-----+-----+
|4 |test4|9 |
+--+-----+-----+
```
I want to add all the values from "*test*" table by using sql query
```
DROP PROCEDURE IF E... | Try this:
```
SELECT SUM(a.value)
FROM test a
```
**OR**
```
SELECT (@value:=@value+a.value) val
FROM test a, (SELECT @value) b
ORDER BY val DESC LIMIT 1
``` | Not sure why do you need loop, but you can use SUM operator:
```
SELECT sum(`value`) FROM `test`
``` | How to perform loop in mysql query? | [
"",
"mysql",
"sql",
"select",
"stored-procedures",
"sum",
""
] |
I hv the following table :-

I need to convert it into:-

Do take note that the date of TIMEINA must follow exactly as per TIMEIN1. As for the time, it will be fixed ie 7.30AM, 8.3... | You should post your code as code and not as an image.
In any case, your code is comparing a `datetime` to a `time` value. Just do a conversion. Instead of `timein1 between . . .`, use:
```
cast(timein1 as time) between . . .
```
EDIT:
Oh, you also need to get the full date out. For that, use arithmetic on `datetim... | The main question I have is how many queries are going against this table?
If you are doing this complex logic in one report, then by all means use a SELECT.
But it is crying out to me for a better solution.
**Why not use computed column?**
Since it is a date and non-deterministic, you can not use the persisted key... | Convert Date & Time | [
"",
"sql",
"sql-server",
""
] |
I am working on PostgreSQL 9.1.4 .
I am inserting the data into 2 tables its working nicely.
I wish to apply transaction for my tables both table exist in
same DB. If my 2nd table going fail on any moment that time my 1 st
table should be rollback.
I tried the properties in "max\_prepared\_transactions" to a non zer... | in postgresql you cannot write commit or roll back explicitly within a function.
I think you could have use a begin end block
just write it simple
```
BEGIN;
insert into tst_table values ('ABC');
Begin
insert into 2nd_table values ('ABC');
EXCEPTION
when your_exception then
ROLL BACK;
END;
END;... | Probably you didn't started transaction.
Please, try
```
BEGIN;
INSERT INTO first_table VALUES(10);
-- second insert should fail
INSERT INTO second_table VALUES(10/0);
ROLLBACK;
``` | Transaction roll back not working in Postgresql | [
"",
"sql",
"postgresql",
"postgresql-9.1",
"phppgadmin",
"php-pgsql",
""
] |
I have the following Django Model:
```
class myModel(models.Model):
name = models.CharField(max_length=255, unique=True)
score = models.FloatField()
```
There are thousands of values in the DB for this model. I would like to efficiently and elegantly use that QuerySets alone to get the top-ten highest scores ... | Of course you can do it in one SQL query. Generating this query using django ORM is also easily achievable.
```
top_scores = (myModel.objects
.order_by('-score')
.values_list('score', flat=True)
.distinct())
top_records = (myModel.objects
... | As an alternative, you can also do it with two SQL queries, what might be faster with some databases than the single SQL query approach (IN operation is usually more expensive than comparing):
```
myModel.objects.filter(
score__gte=myModel.objects.order_by('-score')[9].score
)
```
Also while doing this, you shoul... | How to find top-X highest values in column using Django Queryset without cutting off ties at the bottom? | [
"",
"sql",
"django",
"django-models",
""
] |
I have written a query to create a string and to add padding between the values. This is then exported as a text file in order to load into a legacy system.
I have used a table variable to extract all the source data from table1 then run a query using CAST to create the required string with padding.
My question is; c... | A solution with a CTE would be the following:
```
;WITH cte AS
(
SELECT
source1 + source2 AS column1,
source3 AS column2,
source4 AS column3,
source5 AS column4,
source1 AS column5,
source6 AS column6,
CASE WHEN source7 > 0 THEN ABS(source7) ELSE NULL END AS column7,
CASE WHEN source... | Not sure why you are using the @temp table, but try this:
```
SELECT
CAST(source1 + source2 AS nchar(15)) as column1,
CAST(ISNULL(source2,'') AS nchar(4))+
CAST(ISNULL(column4,'') AS nchar(6))+
CAST(ISNULL(column5,'') AS nchar(14))+
CAST(column1 AS nchar(7)) +
CAST(colu... | SQL Server add padding to a string | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I tried for hours and read many posts but I still can't figure out how to handle this request:
I have a table like this:
```
+------+------+
|ARIDNR|LIEFNR|
+------+------+
|1 |A |
+------+------+
|2 |A |
+------+------+
|3 |A |
+------+------+
|1 |B |
+------+------+
|2 |B |
+... | This ought to do it:
```
SELECT *
FROM YourTable
WHERE ARIDNR IN (
SELECT ARIDNR
FROM YourTable
GROUP BY ARIDNR
HAVING COUNT(*) > 1
)
```
The idea is to use the inner query to identify the records which have a `ARIDNR` value that occurs 1+ times in the data, then get all columns from the same table ba... | Try this please. I checked it and it's working:
```
SELECT *
FROM Table
WHERE ARIDNR IN (
SELECT ARIDNR
FROM Table
GROUP BY ARIDNR
HAVING COUNT(distinct LIEFNR) > 1
)
``` | Select rows with same id but different value in another column | [
"",
"sql",
""
] |
I have this query
```
SELECT
user_id,
played_level,
sum( time_taken ) AS time_take
FROM answer
WHERE completed =1
GROUP BY played_level, user_id
ORDER BY time_take
LIMIT 20
```
This query shows all user id who took minimum time.
But now I want to display only distict user id with his minimum time.
``... | First select all distict user\_id from table
```
$distinct_users = "SELECT DISTINCT user_id FROM answer where addeddate BETWEEN :currdate1 AND :currdate2 AND completed=1";
$distinct_users_data = $conn->prepare($distinct_users);
$distinct_users_data->execute(array(':currd... | ALthough you can do this with a `join`, that is complicated because you have to repeat the aggregation. You can also do this with nested aggregations. The hard part is getting the `played_level` where the minimum occurs. The following query uses a trick to get that using `substring_index()`/`group_concat()`. Here is th... | How to use distinct in group by query? | [
"",
"sql",
"mysql",
"group-by",
"min",
""
] |
Say, I have an organizational structure that is 5 levels deep:
```
CEO -> DeptHead -> Supervisor -> Foreman -> Worker
```
The hierarchy is stored in a table `Position` like this:
```
PositionId | PositionCode | ManagerId
1 | CEO | NULL
2 | DEPT01 | 1
3 | D... | Try a recursive CTE, the example on TechNet is almost identical to your problem I believe:
<http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx> | Thx, everyone suggesting CTE. I got the following code and it's working okay:
```
WITH HierarchyTree (PositionId, PositionCode, Rank)
AS
(
-- Anchor member definition
SELECT PositionId, PositionCode,
0 AS Rank
FROM Position AS e
WHERE PositionCode = 'CEO'
UNION ALL
-- Recursive member definiti... | SQL Server: Select hierarchically related items from one table | [
"",
"sql",
"sql-server",
"hierarchy",
""
] |
I have this table:
```
fy period division employee_id category_name amount
2013 4 Sales 123452 Salary 130000
2013 4 Marketing 124232 Salary 120000
2013 4 Sales-WC 124244 ... | You have to check if the division\_name ends with '-WC' and then strip it off:
```
select
case
when division_name like '%-WC'
then substring(division_name from 1 for position('-WC' in division_name) -1)
else division_name
end,
category_name, SUM(amount) as amount
FROM tblStaff
where fy=2... | I think you want `LIKE`:
```
SELECT
case
when division_name LIKE '%-WC' THEN replace(division_name, '-WC', '')
ELSE division_name
END as 'division_name',
...
```
or you could just do this:
```
SELECT
replace(division_name, '-WC', '') as division_name,
...
GROUP BY replace(division_name, '-WC', '')
... | sum the result of certain rows by comparing string values of column | [
"",
"sql",
"select",
""
] |
My SQL code is fairly simple. I'm trying to select some data from a database like this:
```
SELECT * FROM DBTable
WHERE id IN (1,2,5,7,10)
```
I want to know how to declare the list before the select (in a variable, list, array, or something) and inside the select only use the variable name, something like this:
```... | You could declare a variable as a temporary table like this:
```
declare @myList table (Id int)
```
Which means you can use the `insert` statement to populate it with values:
```
insert into @myList values (1), (2), (5), (7), (10)
```
Then your `select` statement can use either the `in` statement:
```
select * fro... | That is not possible with a normal query since the `in` clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic query
```
declare @myList varchar(100)
set @myList = '1,2,5,7,10'
exec('select * from DBTable where id IN (' + @myList + ')')
``` | SQL Server procedure declare a list | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I really wanted to come up with the solution by myself for this one, but this is turning out to be slightly more challenging than I thought it would be.
The table I am trying to retrieve information would look something like below in simpler form.
Table: CarFeatures
```
+---+---+---+---+-----+
|Car|Nav|Bth|Eco|Radio... | --Aha! I kind of figured out myself (very happy) :). Since the value for the columns can only be 'y' or 'n,' to ignore when the parameters value are no,
-- I will just ask it look for value that will never be there.
--If anyone has a better way of doing it or enhancing what I have (preferred) would be appreciated.
--Th... | Your schema is awkward and denormalised, you should have 3 tables,
```
Car
Feature
CarFeature
```
The `CarFeature` table should consist of two columns, `CarId` and `FeatureId`. Then your could do something like,
```
SELECT DISTINCT
cr.CarId
FROM
CarFeature cr
WHERE
cr.Fe... | Conditional where; Sql query/TSql for SQLServer2008 | [
"",
"sql",
"sql-server-2008",
"t-sql",
"ssrs-2008",
""
] |
In my MYSQL database I have multiple tables like this:
`reference`:
```
------------------------------
| id | title | subtitle |
| 1 | Test | Just a test |
| 2 | Another | Second |
| 3 | Last | Third |
------------------------------
```
`author`:
```
-----------------------------
| id | fir... | I tried to make my query as clear as possible according to the table struture you specified in your question (not what I could see on your queries).
You will probably need to change some field/table name.
You can have a look on the query result here : `SQLFiddle demo`
```
SELECT
r.id
,r.title
,r.subtitle
... | Maybe?
```
SELECT r.*,
GROUP_CONCAT(CONCAT_WS(\' \', CONCAT(a.lastname, \',\'), a.prefix, a.firstname) SEPARATOR \'; \')) AS author,
GROUP_CONCAT(CONCAT_WS(\' \', k.keywords) AS keywords
FROM references AS r
LEFT OUTER JOIN (SELECT * FROM references_has_authors AS rha INNER JOIN authors AS a ON a.id = rha.authors_id) ... | Optimize Subselect Search query | [
"",
"mysql",
"sql",
"query-optimization",
""
] |
so i need to get the sum of 20+ columns in a table that i'm working with and i'd really like to not have to write out the sum of every single column but i'm not sure that is possible. is there a way to get this to be dynamically written for all the columns in the table?
```
select isnull(osname, 'Total'), COUNT(*), SU... | First and foremost, if you can automate something, please do. Typing out 20, 100 columns definitely is tedious.
My solution below uses a Table Variable Function to the get the list of numbered columns. This can be reused again.
Second, I create some dynamic T-SQL using this function and applying your logic. The WITH ... | I would run:
```
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'usage'
```
Then I would copy the columns into excel or google spreadsheet.
Then make column B in excel:
```
="SUM(" & A1 & "),"
```
And then copy that to all appropriate B cells. | Sum each column for a table with over 20 columns without writing out each sum | [
"",
"sql",
"sql-server",
""
] |
```
SELECT
*, (SELECT count(1) from color i WHERE i.NAME <= c.NAME)
FROM color c
ORDER BY name
```
Output:
```
id NAME
----------- ------------------------- -----------
4 blue 1
1 orange 2
3 red ... | It's a correlated subquery. For each row in `c`, count the number of rows in the same table, with the same name or a lower name.
This is an absolutely inefficient and wasteful way to generate a row number, but is likely the most common way people worked around the lack of such a function in, say, SQL Server 2000. Toda... | the subselect
```
select count(1) from color i where i.name <= c.name)
```
counts the rows where the name is smaller or equal to the name in the current row of the outer select, thus counting the rows up to that point. you can confuse it by having a colour twice in that table. try inserting red again and see what hap... | row_nums without using row_number function? | [
"",
"sql",
"sql-server",
""
] |
I have the following SQL statement. Which is working okay. Except in some cases the processing of the query takes a lot of time, resulting in a system time out. So I need to convert the statement. Probably with a JOIN.
I can't figure out how to convert this statement:
```
SELECT table1.id as id,
table1.firstn... | ```
select t1.id,t1.firstname,t3.name,t4.name
from table1 as t1
inner join table2 as t2 on t1.id=t2.tabel1id
inner join on table3 as t3 on t2.table2id=t3.table2id
inner join on table4 as t4 on t3.table3id=t4.name
inner join on table5 as t5 on t5.table3id=table3.table3id
where t1.firstname like '%John%' and t5.somec... | You already have JOINs, but you use the implicit version (comma-delimited table list in FROM plus join-conditions in WHERE) instead of the explicit (JOIN plus ON).
So rewriting should not improve performance (otherwise MySQL is more crappy than I thought).
You should better check if you created all neccessary indexes... | Converting complex SQL to JOIN | [
"",
"mysql",
"sql",
"sql-server",
"subquery",
"inner-join",
""
] |
When we make a SQL request like this:
```
SELECT attr1, attr2, AGGR(*)
FROM SomeTable
GROUP BY attr1, attr2
```
for some aggregate function, we have to include a GROUP BY clause and list attr1 and attr2 in it. My question is: why doesn't the SQL DBMS do it itself? | Because you may want to group by `attr1`, `attr2` *and* `attr3`, even though you have no interest in the actual `attr3` value itself.
In other words, you may be required to group by the non-aggegated columns but this in only at a minimum. There's nothing preventing you from grouping by columns not actually included in... | You could do it with out `GROUP BY`, then you get the average from the whole table.
With `GROUP BY`, you get the average for each group. | Why we use group by in sql | [
"",
"sql",
"group-by",
""
] |
Please update title as I didn't got any suitable one and remove this comment ;)
I have a table having data like:
`id``assigned_to``foreign_id``purchase_date`
`1``5`
`1`
`2014-01-01`
`4``7`
`1`
`2014-01-09`
`6``2`
`1`
`2014-01-10`
`8``9`
`1`
`2014-01-13`
`12``9`
`2`
`2014-01-13`
`18``9`
`3`
`2014-01-... | Put the filter on `foreign_id` into the `WHERE` clause and the filter on `assigned_to` into the `ORDER BY` clause and add LIMIT 1, like this:
```
SELECT
id,
assigned_to,
foreign_id,
purchase_date
FROM
atable
WHERE
foreign_id = @foreign_id
ORDER BY
assigned_to = @assigned_to DESC,
purchase_date ... | You can use case...when in mysql with count() function.
Check out following link:
<http://www.mysqltutorial.org/mysql-case-statement/> | MySQL: Fetch conditional rows only, from a query dataset | [
"",
"mysql",
"sql",
"optimization",
""
] |
Not getting the value of `@lastupdate`. If removing the `SELECT` statement, then getting the value of `@lastupdate` in codebehind
```
@action int,
@autoid int = NULL,
@datecheck date = NULL,
@lastupdate datetime = '' OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF @action = 1
BEGIN
SET @lastupdate = (SELECT reddate F... | Any output parameters are returned after the results set. Make sure you have processed/read the results before trying to access the output parameter. | From what I can see you should be using something along the lines of the following:
```
SELECT @lastupdate = reddate FROM lastupdate
```
Though personally I would probably limit the query as this could take a while depending on database size etc. | Select statement with output clause doesn't work | [
"",
"sql",
""
] |
Lets say we have such table:

i only what to select unique plans with highest time, and also being able to select other columns. To ilustrate here's a query(witch obviously wouldn't work):
```
SELECT DISTINCT(plan), time, id
FROM table
ORDER BY time desc
```
how can i ge... | SELECT plan, max(time), id
FROM demo group by plan
[check fiddle](http://sqlfiddle.com/#!9/7483c/7) | This sounds like a simple aggregate query:
```
SELECT plan, MAX(time)
FROM mytable
GROUP BY plan
``` | SQL select distinct only highest values | [
"",
"mysql",
"sql",
"select",
"distinct",
""
] |
Not sure that title clears my question. What i need is:
TABLE: id, year
Example data:
```
+--+----+
|id|year|
+--+----+
|1 |1990|
+--+----+
|2 |1990|
+--+----+
|3 |1990|
+--+----+
|4 |1992|
+--+----+
|5 |1992|
+--+----+
```
On input i receive an ID. For id 1 result must be 3 (cause 3 rows shares the same year as row ... | ```
SELECT t2.id, t1.year, count(*)
FROM TEMP t1 INNER JOIN TEMP t2 ON t1.year=t2.year
GROUP BY t1.year, t2.id
```
Look at <http://sqlfiddle.com/#!7/38b05/4> | First extract distinct year name using
```
String selectQuery = "SELECT DISTINCT year FROM "+TABLE_NAME;
```
Result of this query will be
```
1990
1992
```
After getting this you can use to get all the row for selected year
```
String query = "Select * from "+TABLE_NAME+ " where year = '"+year
```
You can store t... | How to get row count with same field value as from row with provided id? | [
"",
"android",
"sql",
""
] |
I have a query that looks like this:
```
select Group, Sum(columnA) as SumColumn
FROM table
GROUP BY Group
```
I get results looking like this
```
+-----+---------+
|Group|SumColumn|
+-----+---------+
|A |10 |
+-----+---------+
|B |20 |
+-----+---------+
```
How can I change/add to this to show so... | It is hard to see what your data looks like -- but from what you posted this is what you want:
```
SELECT Name,
SumColumn,
SUM(SumColumn) AS TotalColumn
FROM
(
SELECT Group as Name, SUM(columnA) AS SumColumn
FROM Table
GROUP BY Group
) T
```
You might want this -- depending on other stuff.... | You can actually mix window functions and aggregation functions in a `select` statement. So, you can do this without subqueries:
```
select Group, Sum(columnA) as SumColumn,
sum(sum(columnA)) over () as TotalColumns
FROM table
GROUP BY Group;
``` | sum column to show total in every row | [
"",
"sql",
"t-sql",
"sql-server-2005",
""
] |
To start: I am querying a DB2 server built into the IBM i System package from Excel 2007 using "From Microsoft Query" and straight-up SQL. It is a financial database.
The DB is structured such that account #s are split up into 8 integer fields for fund, division, department, activity 1, activity 2, element 1, element ... | Am assuming the error is SQL0206 - Column or global variable AJAccount not found.
If true, the problem is that the GROUP BY clause is looking for a column in the database table, not a derived column in the SELECT clause. Try putting the entire derived column in your GROUP BY:
```
select...
where...
group by right(tri... | A simplified example using a [common-table-expression](http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/topic/db2/rbafzcomtexp.htm):
```
WITH gm310ap AS (SELECT
RIGHT('00'||DIGITS(gmfund),3) || '-' ||
RIGHT('0'||DIGITS(gmdpt),2) ||
RIGHT('0'||DIGITS(gmdiv),2) || '-' ||
RIGHT('0'||DIGITS(gmstab),2) |... | Summing over a calculated field of concatenated strings (split acct #s) | [
"",
"sql",
"db2",
"excel-2007",
"ibm-midrange",
""
] |
I have two tables:
1. `subject` which holds a list of subjects and their credits
2. `exams` which shows which subjects the students failed or succeeded in the exams
I am trying to get a list of total credits earned for every student. Problem is if a student failed in all subjects he doesn't show up cause he's filtere... | Try this
```
CREATE VIEW student_credits AS
SELECT a.student, SUM(CASE WHEN a.success then b.credits
else 0 end) AS total_credits FROM
exam a INNER JOIN
subject b ON b.name = a.subject
GROUP BY a.student;
``` | I did:
```
CREATE VIEW student_credits AS
SELECT a.student, SUM(b.credits) AS total_credits FROM
exam a INNER JOIN
subject b ON b.name = a.subject
WHERE a.success IS TRUE
GROUP BY a.student
UNION
SELECT DISTINCT STUDENT, 0 AS total_credits FROM exam a
WHERE NOT EXISTS (SELECT 1 FROM exam b WHERE b.student=a.student... | group by and SUM only rows satisfying a criterion, but show the others too | [
"",
"sql",
"postgresql",
"group-by",
""
] |
I'm developing an online shop application which includes a table named 'tbl\_items'. The primary key for each item is the 'item\_id' field.
Now, I want to add an option for each item posted on the shop to be associated with multiple pictures describing the item (unlimited amount of pictures per item), so I created ano... | This is a very common design pattern, and putting both columns into a PK is the normal solution. If you **don't** do this you will potentially have multiple links from an item to the same picture.
There's nothing wrong with putting both columns into a PK for this.
**Update:**
to recap....
1 - Put your pictures into... | You have 3 possibilities:
1.) Have no primary key. atm you seem not to need one.
2.) If `item_id` and `url` are unique together use both as primary key
3.) add a third column (like `picture_id`) and fill it manually or automatically from a sequence
Good luck! | Table Structure (Missing Primary Key) | [
"",
"sql",
""
] |
What's the difference between:
```
select t1.a1, t1.a2, t1.a3 from t1 cross join t2 where t1.a3 = t2.a1
```
and:
```
select t1.a1, t1.a2, t1.a3 from t1,t2 where t1.a3=t2.a1;
```
Can I use them interchangeably? | MySQL doesn't offer a distinction between `JOIN` and `CROSS JOIN`. They are the same.
In both your examples the clause
```
WHERE t1.a3 = t2.a1
```
converts any sort of join into an inner join. The standard way of expressing this query is
```
SELECT t1.a1, t1.a2, t1.a3
FROM t1
JOIN t2 ON t1.a3 = t2.a1
``` | SQL has the following types of joins, all of which come straight from set theory:
* **Inner join.**
`From A inner join B` is the equivalent of A ∩ B, providing the set of elements common to both sets.
* **Left outer join.**
`From A left outer join B` is the equivalent of (A − B) ∪ (A ∩ B). Each A will appear a... | In SQL, what's the difference between JOIN and CROSS JOIN? | [
"",
"mysql",
"sql",
"join",
"cross-join",
""
] |
How can I INSERT INTO an **empty** field **without creating a new row**?
If I understand:
I cannot use `insert` into with a `where` clause:
```
INSERT INTO consulta (tema)
value('prova')
WHERE client=1;
```
I can `update` with a `where` but I cannot do that if the field is empty :
```
UPDATE consulta
SET... | I think you're trying to update actually, insert into is allways intended for creation, unless you use replace into which will over write your row ONLY IF there if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, (From [Mysql 5 reference](http://dev.mysql.com/doc/refman/5.0/e... | Do you want one of these?
```
UPDATE consulta
SET tema=prova
WHERE client is null;
```
or
```
UPDATE consulta
SET tema=prova
WHERE client = '';
```
"Empty" doesn't have a technical meaning in SQL, so it could be either. | Insert in an existing row | [
"",
"sql",
"insert",
"sql-update",
""
] |
This is a trivial example, but I am trying to understand how to think creatively using SQL.
For example, I have the following tables below, and I want to query the names of `folks` who have three or more `questions`. How can I do this without using `HAVING` or `COUNT`? I wonder if this is possible using `JOINS` or som... | Using `SUM` or `CASE` seems to be cheating to me!
I'm not sure if it's possible in your current formulation, but if you add a primary key to the question table (`questionid`) then the following seems to work:
```
SELECT DISTINCT Folks.folkid, Folks.name
FROM ((Folks
INNER JOIN Question AS Question_1 ON Folks.folki... | you can try sum , to replace count.
```
SELECT SUM(CASE WHEN Field_name >=3 THEN field_name ELSE 0 END)
FROM tabel_name
``` | SQL : How to find number of occurrences without using HAVING or COUNT? | [
"",
"sql",
""
] |
I mistyped a query today, but it still worked and gave the intended result. I meant to run this query:
```
SELECT e.id FROM employees e JOIN users u ON u.email=e.email WHERE u.id='139840'
```
but I accidentally ran this query
```
SELECT e.id FROM employees e JOIN users u ON u.email=e.email AND u.id='139840'
```
(no... | For inner joins like this they are logically equivalent. However, you can run in to situations where a condition in the join clause means something different than a condition in the where clause.
As a simple illustration, imagine you do a left join like so;
```
select x.id
from x
left join y
on x.id =... | In the case of an INNER JOIN, the two queries are semantically the same, meaning they are guaranteed to have the same results. If you were using an OUTER join, the meaning of the two queries could be very different, with different results.
Performance-wise, I would *expect* that these two queries would result in the s... | INNER JOIN condition in WHERE clause or ON clause? | [
"",
"mysql",
"sql",
"performance",
"inner-join",
""
] |
I am trying to fix an order problem for a column in a SQL table. The column has dates but with the type `varchar`, and they are in this format: `mm/dd/yy`. I did not make it this way, the person behind me did and left.
How do I change all the entries to be the format `yyyy/mm/dd`? Once I put them in this format I will... | Do it like this, using [STR\_TO\_DATE](http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html#function_str-to-date):
* Add a `date` column (called `newdate` for example)
* Execute this:
`UPDATE table SET newdate = STR_TO_DATE(olddate, '%m/%d/%y');`
* Test it
* Drop the old column and optionally rename the n... | You can do it with string manipulations:
```
update t
set col = concat('20', right(col, 2), '/', left(col, 5))
where col like '%/%/%'
``` | How do I correct date values in a SQL table? | [
"",
"mysql",
"sql",
"database",
"algorithm",
""
] |
I tried to search for this but maybe I'm looking for it incorrectly.
This is for an android app.
Essentially, I want to search the database based on some criteria (e.g. subcategory and item name), then use some of the other data values in the row to do a calculation (e.g. get the price value, and use it for a calculat... | You can use [aggregate functions](http://www.sqlite.org/lang_aggfunc.html) to compute a single value based on a column's value in multiple records:
```
SELECT AVG(price) FROM prices WHERE subcat = 'meat' AND item = 'lamb'
``` | After creating your cursor, get the index(es) of the column(s) you want to read. For example, if one of the columns returned by SELECT \* is price, the following gives the position of that column in each cursor row:
```
int PRICE_INDEX = d.getColumnIndexOrThrow("price");
```
Then you need to iterate over the results ... | Search SQLite Database and use values from retrieved rows for calculation | [
"",
"android",
"sql",
"sqlite",
"search",
"calculated-columns",
""
] |
I need to get the extensions of filenames. Extensions could be any length (not just 3) and they could also be non-existent, in which case I need `null` returned. I know I could easily write a PL/SQL function that does this then just call that function in the query but I was hoping that I could somehow do it all inline.... | It will run fastest when done 100% sql, as you have.
The substr/instr are native compiled functions in oracle.
If you put this in a plsql function it will run slower due to context switching between sql and plsql:
This is slower due to context switching:
```
select extrip( filename ) from million_row_table
```
Wha... | You need to use regular expressions.
Try
```
select regexp_substr(filename, '\.[^\.]*$')
from
(select 'no_extension_should_return_null' filename from dual);
```
I don't have an Oracle database to test this on but this should be pretty close.
Check the [Oracle docs on regexp\_substr](http://docs.oracle.com/cd/B1... | Oracle: Fastest Way to Extract Filename Extension Using SQL or PL/SQL | [
"",
"sql",
"oracle",
"plsql",
""
] |
I've had a SQL performance review done on a project we're working on, and one 'Critical' item that has come up is this:
> This kind of wildcard query pattern will cause a table scan, resulting
> in poor query performance.
```
SELECT *
FROM TabFoo
WHERE ColBar = @someparam OR @someparam IS NULL
```
Their recommend... | A query like
```
select *
from foo
where foo.bar = @p OR @p is null
```
might or might not cause a table scan. My experience is that it will not: the optimizer perfectly able to do an index seek on the expression `foo.bar = @p`, assuming a suitable index exists. Further, it's perfectly able to short-circuit things if... | I could be wrong, but I'm pretty sure a table scan will occur no matter what if the column you have in your `where` clause isn't indexed. Also, you could probably get better performance by reordering your `OR` clauses so that if `@ParA IS NULL` is true, it evaluates first and would not require evaluating the value in t... | Wildcard Pattern usage | [
"",
"sql",
"sql-server",
""
] |
I have the query listed below, it is out from a PDO statement. Everything in the query works fine, apart from the collectionId = 3 part. Its returning results with other intergers...
I've stared at this for a while and can't spot what is wrong, it all looks fine to me?
```
SELECT `Hat`.`id` AS `Hat_id` , `Hat`.`ha... | Your OR conditions need to be in parentheses:
```
SELECT `Hat`.`id` AS `Hat_id` , `Hat`.`hatCode` AS `Hat_hatCode` , `Hat`.`hatCodeOther` AS `Hat_hatCodeOther` , `Hat`.`name` AS `Hat_name` , `Hat`.`description` AS `Hat_description` , `Hat`.`colorId` AS `Hat_colorId` , `Hat`.`collectionId` AS `Hat_collecti... | Can you try this, Added `()` for OR grouping
```
WHERE (
`Hat`.`published` =1
AND `Hat`.`collectionId` = '3'
AND ( `Hat`.`colorId` LIKE '%||2||%'
OR `Hat`.`colorId` LIKE '2||%'
OR `Hat`.`colorId` LIKE '%||2'
OR `Hat`.`colorId` LIKE '2'
)
)
```
Ref: [SQL Query multiple AND and OR's not working](https://stacko... | mysql query not filtering AND as expected | [
"",
"mysql",
"sql",
""
] |
Here's my sql statement:
```
SELECT
tA.a1, GROUP_CONCAT(tB.b2) AS b2
FROM
tableA tA
LEFT JOIN
tableB tB ON tA.a2 = tB.b1
WHERE
CONCAT(tA.a1, b2) LIKE '%somestring%'
GROUP BY tA.a1;
```
I get an sql error saying something along the lines of "unknown column name b2 in WHERE". | You can't use aliases in `WHERE` clause - but in your case that's even senseless, because `WHERE` applies filter to rows that **will be grouped** while `GROUP_CONCAT()` collects rows that are **already grouped**
You may do that, for example, with subquery:
```
SELECT *
FROM
(SELECT
tA.a1 AS ta1, GROUP_CONCAT(t... | ```
SELECT
tA.a1, GROUP_CONCAT(tB.b2) AS b2
FROM
tableA tA
LEFT JOIN
tableB tB ON tA.a2 = tB.b1
GROUP BY tA.a1
HAVING
CONCAT(tA.a1, b2) LIKE '%somestring%';
``` | SQL GROUP_CONCAT alias in WHERE | [
"",
"mysql",
"sql",
""
] |
In a table within my database there is a varchar2 column that mostly consists of numbers. Now I want to receive the NUMERICAL maximum of that column, ignoring non-numerical values.
How do I do that?
Thank you. | ```
SQL> select * from t;
X
----------
1234
836 ... | There are so many traps and exceptions when you try to convert a string into a number. I use a function like this:
```
FUNCTION Is_Numeric(Expression IN VARCHAR2) RETURN INTEGER
BEGIN
IF TO_NUMBER(Expression) IS NOT NULL THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
EXCEPTION
WHEN VALUE_ERROR OR... | Oracle-SQL Query to obtain the maximum value of a column that has been converted from String to Integer | [
"",
"sql",
"oracle",
""
] |
The table name is "OrderDetails" and columns are given below:
```
OrderDetailID || ProductID || ProductName || OrderQuantity
```
I'm trying to select multiple columns and Group By ProductID while having SUM of OrderQuantity.
```
Select ProductID,ProductName,OrderQuantity Sum(OrderQuantity)
from OrderDetails Group ... | I use this trick to group by one column when I have a multiple columns selection:
```
SELECT MAX(id) AS id,
Nume,
MAX(intrare) AS intrare,
MAX(iesire) AS iesire,
MAX(intrare-iesire) AS stoc,
MAX(data) AS data
FROM Produse
GROUP BY Nume
ORDER BY Nume
```
This works. | I just wanted to add a more effective and generic way to solve this kind of problems.
The main idea is about working with sub queries.
do your group by and join the same table on the ID of the table.
your case is more specific since your productId is **not unique** so there is 2 ways to solve this.
I will begin by t... | Select multiple columns from a table, but group by one | [
"",
"sql",
"group-by",
""
] |
I am trying to write a SQL SELECT statement to find out the most recently hired employees in EACH department. I am working on Oracle database and am trying to display the department name, employee name, hire date, and salary. The table definition for employee and department tables are below
Department Table
```
CREATE... | You can do it by join
```
SELECT dpt.department_name, dpt.department_id, employee_name, hire_date, Salary
from dpt inner join emp on emp.department_id = dpt.department_id inner join
(select emp.department_id, max(hire_date) as datemax from emp) x on emp.department_id=x.department_id and emp.hire_date =x.date... | You are missing a table alias on the `where` clause in the correlated subquery:
```
SELECT dpt.department_name, dpt.department_id, employee_name, hire_date, Salary
from dpt join
emp
on emp.department_id = dpt.department_id
where hire_date = (select max(hire_date) from emp emp2 where emp.department_id = emp2... | SQL query _ not able to find recently hired employee is each department | [
"",
"sql",
"oracle",
""
] |
I have 2 tables:
* groups
* contacts
groups table's fields are:
* group\_id
* group\_name
contacts table fields are:
* contact\_group\_id
* contact\_id
* contact\_name
Now, I want to select all groups with count of group's contacts...
For e.g.:
groupname contacts count
friend 12 |
school 8 |
ennemy 0 |
family ... | you need to do left join and then group by. Do following
```
select a.group_name, count(b.contact_id) from
groups a left join contacts b on
a.group_id = b.contact_group_id
group by a.group_name
```
See [Fiddle](http://sqlfiddle.com/#!6/3f98a/3) | Create a view containing the number of contacts per group and then outer join that view with your groups table.
```
CREATE VIEW contactscount AS
SELECT contact_group_id, COUNT(contact_id) AS count FROM contacts GROUP BY contact_group_id
SELECT * FROM groups OUTER JOIN contactscount ON contactscount.contact_group_id=g... | how do select all rows from table groups and count of contacts for each groups in sql | [
"",
"sql",
""
] |
I'm having difficulty finding the answer for this in my searching. This is a sample table:
```
1 | Bob Smith |
2 | Mary Jones |
3 | Paul Bunyon |
4 | Bob Smith |
5 | Bob Smith |
6 | Mary Jones |
7 | Tim Gunn |
```
I'd like to select a distinct amount of names BUT, I need the count of number of times that name is in ... | `Group By` + `Count(*)` , you need to cast the `int` to `varchar`:
```
SELECT NameCount = Name + CASE WHEN COUNT(*) = 1 THEN ''
ELSE ' (' + CAST(Count(*) as varchar(10)) + ')' END
FROM dbo.Table1
GROUP BY Name
```
`Demo` | You want the number to be in parentheses *conditionally* when it is greater than 1:
```
select (case when count(*) = 1 then Name
else concat(Name, ' (', Count(*), ')')
end)
from t
group by Name;
```
SQL Server 2012 supports the ANSI standard `concat()` function. And, it take numeric arguments so ... | Returning count after name if more than one record | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I am trying to write a query in sql server:
table:
```
SELECT [Id]
,[BrokerId]
,[UserId]
FROM [UserBroker]
```
values I want to grab:
```
Id BrokerId UserId
21288 252055 223177
21291 252055 223178
```
attempt at query:
I want to grab all records that have duplicate userids to on... | ```
Select UB.ID, UB.BrokerID, UB.userId
FROM userBroker ub
INNER JOIN userBroker mUB
on Ub.BrokerID = mub.BrokerID
and Ub.userID <> mub.UserID
GROUP BY UB.ID, UB.BrokerID, UB.userId
ORDER BY UB.BrokerID, UB.userId, UB.Id
```
Returns ID, broker and userIDs where different userID's exist for the same broker. Note the... | ```
WITH t AS (
SELECT *,
COUNT(*) OVER(PARTITION BY [BrokerId], [UserId]) c
FROM [UserBroker]
)
SELECT [Id], [BrokerId], [UserId]
FROM t
WHERE c > 1
``` | sql grab duplicate record with same second column | [
"",
"sql",
"sql-server",
""
] |
What is the difference between `ColumnName = Null` and `ColumnName Is Null` in SQL Server? I have researched about this but I didn't get any clarification.
Actually I want to retrieve column has null value
```
Select * from Table1 where column1 is null
```
This query returning expected result but the following query... | Comparisons with null using normal operators are never true.
That's basically because null is "unknown" so it can't be determined whether it is or is not some value.
The special syntax `is null` and `is not null` must be used to determine nullness. | Using [comparison](http://technet.microsoft.com/en-us/library/ms188074.aspx) operators on `NULL` will result un `Unkown result`
Take a look at the following example:
```
Declare @temp table
(
val1 int,
val2 int
)
INSERT INTO @temp
VALUES (1,NULL),
(NULL,1),
(NULL,NULL)
SELECT CASE
WHEN val... | Difference between ColumnName = Null and ColumnName Is Null in SQL Server | [
"",
"sql",
"sql-server",
""
] |
here is my query string
`SELECT
Payment
,Balance
,PatientNo
FROM
[GP_DB].[dbo].[GP]
where GP.GPDate= (SELECT CONVERT(VARCHAR(24),@GPDate,103))`
GPDate is a Date type column, not DateTime
and i pass parameter like this
```
cmd_select_treatment.Parameters.AddWithValue(
"@GPDate"
,C... | @var is DateTime
select cast(convert (varchar(8),@var,112) as Date) | > GPDate is a Date type column
If it's a `DATE` column and your `Convert.ToDateTime` call returns a `DateTime` object then don't bother yourself with the `CAST`.
```
WHERE GP.GPDate = @GPDate
```
If `dateTimePicker1` might contain a time component and you don't care for that then simply discard it before using its v... | how to solve Passing DateTime value to paramaterized query Error | [
"",
"sql",
"datetime",
"datetimepicker",
"sql-convert",
""
] |
I have a database as such
```
Update Record_ID Index Location
1 1 23 China
1 1 24 Beijing
1 1 45 Norway
1 1 23 China
2 1 423 Somne
2 1 ... | ```
SELECT * FROM table t1
JOIN (SELECT Record_ID ,MAX(Updates)as maxupdate FROM table GROUP BY Record_ID)x
ON t1.Record_ID = x.Record_ID AND t1.Updates=x.maxupdate
```
[Fiddle](http://sqlfiddle.com/#!2/bfcdb/1)
It also works for multiple Record\_id | Try This
```
SELECT * FROM Table_Name
WHERE `Update` = (SELECT TOP 1 `Update` FROM Table_Name ORDER BY ID DESC)
``` | Get last record in mysql table | [
"",
"mysql",
"sql",
"database",
""
] |
How can I create an SQL select query to return variable as true(1) if a column value exists in a table else false(0).
I want to use this variable in my scripts so that
if variable=1
execute A
ELSE
execute B | In Oracle you can use something like this
```
SELECT
CASE nvl(length(column1), 0)
WHEN 0 THEN 0
ELSE 1
END AS column1
FROM yourTableName;
``` | You can try this...
```
IF ((SELECT COUNT(*) FROM TableName WHERE FieldName = 'Whatever') <> 0)
-- Execute something if column value exists
ELSE
-- Execute something if column value does not exist
``` | SQL query with variable ,IF & select staement | [
"",
"mysql",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I have a relational database in SQL Server which I use to store Products, Competitor Companies and Competitor Prices. I regularly add new records to the Competitor Prices table rather than updating existing records so I can track prices changes over time.
I want to build a query which given a particular product, find ... | As an alternative, you can also use `ROW_NUMBER()` which is a Window function that generates sequential number.
```
SELECT cp_id,
product_id,
competitor_id,
price,
date_added
FROM (
SELECT cp_id,
product_id,
competitor_id,
... | Try this,
```
SELECT cp_id, product_id, competitor_id, price, date_added
FROM tblCompetitorPrices
WHERE product_id = '1' AND date_added=( SELECT MAX(date_added)
FROM tblCompetitorPrices
WHERE product_id = '1')
ORDER BY date_added DESC
``` | Confusing SQL Query, Group By? Having? | [
"",
"sql",
"sql-server",
"rdbms",
""
] |
I've looked at many SO questions related to this but I can't seem to get anything to work. I'm not very good with semi complex SQL queries.
I want to get the difference between the current time and a column that is in unix timestamp in hours.
I'm not sure what I'm doing wrong or right for that matter. The goal is to ... | From the [fine manual](http://www.postgresql.org/docs/current/interactive/functions-formatting.html):
> A single-argument `to_timestamp` function is also available; it accepts a `double precision` argument and converts from Unix epoch (seconds since 1970-01-01 00:00:00+00) to `timestamp with time zone`. (`Integer` Uni... | Try:
```
SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamo_A))
FROM TableA
```
Details here: [EXTRACT](http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT). | PostgreSQL get time difference between timestamps | [
"",
"sql",
"postgresql",
"timestamp",
""
] |
```
+-------+-----------+------+----------------------+----------------------+
|RATE_ID|DESCRIPTION|CHARGE|FROM_DATE |TO_DATE |
+-------+-----------+------+----------------------+----------------------+
|1 |small |100 |01/01/2014 12:00:00 AM|31/03/2014 12:00:00 AM|
+-------+-------... | You can use CONNECT BY to generate the list of days between end and start date and join this list with the list of rates:
```
with v_days as (
SELECT TRUNC (to_date('2014-04-05', 'YYYY-MM-DD') - ROWNUM + 1) dt
FROM DUAL
CONNECT BY ROWNUM <= (to_date('2014-04-05', 'YYYY-MM-DD') + 1 -
to_date('2014-03-30', ... | The DATEDIFF() function returns the time between two dates.
```
SELECT DATEDIFF(day,'01-01-2014','31-03-2014') AS DiffDate
```
And consider the date format to get the correct result.
Please refer below link for further information
<http://www.w3schools.com/sql/func_datediff.asp> | find number of days exists within a date range | [
"",
"sql",
"oracle",
"date",
"date-range",
""
] |
I am connecting to Hive via an ODBC driver from a .NET application. Is there a query to determine if a table already exists?
For example, in MSSQL you can query the `INFORMATION_SCHEMA` table and in Netezza you can query the `_v_table` table.
Any assistance would be appreciated. | There are two approaches by which you can check that:
1.) As @dimamah suggested, just to add one point here, for this approach you need to
```
1.1) start the **hiveserver** before running the query
1.2) you have to run two queries
1.2.1) USE <database_name>
1.2.2) SHOW TABLES LIKE 'table_name'
1.2... | Execute the following command : `show tables in DB like 'TABLENAME'`
If the table exists, its name will be returned, otherwise nothing will be returned.
This is done directly from hive. for more options see [this](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-ShowTables/Parti... | How to check if a table exists in Hive? | [
"",
"sql",
"odbc",
"hive",
""
] |
I've got a project with a lot of SQL-queries compiled in \*.DLLs files.
Yesterday, I've received a new bug: username (which generated automatically) with single quote causes an error.
The reason is queries like this one:
```
string.Format("SELECT TimeZone from yaf_User WHERE [Name]='{0}'", UserName);
```
Can... | What you are doing is dangerous because it lends itself to SQL injection attacks (as a side effect it also causes the issue you're seeing.
The solution is to use parameterised queries - this also avoids SQL injection attacks.
```
SqlCommand cmd = new SqlCommand("SELECT TimeZone from yaf_User WHERE [Name]=@UserName"),... | This is for Chris. Escaping characters may work. If the person is clever, the are some ways around it.
For instance.
```
-- Use Adventure works
use adventureworks2012
go
```
Say, I know you are replace a single quote with two, your chosen solution on the answere line. Enter the following
**Bothell'; GRANT CONTROL T... | MSSQL: single quotes causes to error in queries | [
"",
"sql",
".net",
"sql-server",
""
] |
I have a table of comtent like bellow...
```
ProjectID | ParentID | Project Name ...
----------------------------------------
1 | 1 | Project Name 1...
2 | 2 | Project Name 2...
3 | 3 | Project Name 3...
4 | 1 | Pr... | I found the way to solve. But the actual solution is given by [Jayvee](https://stackoverflow.com/users/2964963/jayvee). Sorry I didnt know the method it calls, so I think I didnt explain it perfectly. Actually I want to use recursion here on aspect of ProjectID.
```
DECLARE @ProjectID int = 1
WITH DirectReports
AS
(
... | I think the easiest way to find this is to search the `ProjectName` column. It appears to contains the hierarchy information:
```
select c.*
from content c
where ProjectName+' ' like '%Project 1 %'
```
The additional space is to be sure that `Project 1` does not match `Project 10`. | Get data from same table with the compare of multiple rows? | [
"",
"sql",
"t-sql",
""
] |
I'm executing a SQL command to create a new record in a database table and get the ID of the created record. However, there's a constraint error generated by the SQL command (uninitialized non-null field) which is not being picked up by the VB code. The code is roughly:-
```
connection = New SqlConnection(connection_s... | The `HasRows` call returns false if there is an error. That way you will never see the error. Remove both `If` statements. The null check is redundant, the other one suppresses errors. | The severity level is 16 which does not interrupt the current session. If you want to throw a hard error you could add something like this directly after your insert...
```
If @@Error <> 0
Begin
Raiserror('Constraint Error Encountered',20,1) With Log;
End
```
The security context will have to have sys... | SqlCommand.ExecuteReader Fails to Report Errors | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
I have 2 SQL Oracle datatables.
```
A: Col1 | Col2 | Key
c1 c2 1
c3 c4 2
c5 c6 3
B: Co1 | Co2 | Key
a1 a2 2
a3 a4 3
```
I need select that gives me following table:
```
C:
a1 a2 c3 c4
a3 a4 c5 c6
- - c1 c2
```
How can I do i... | You need a left outer join:
```
select b.col1, b.col2, a.col1, a.col2
from a left outer join
b
on a.key = b.key;
``` | When doing a join like you are it will only return entries that exist in both tables. To get the result that you are looking for try something like this...
```
SELECT B.Co1, B.Co2, A.Col1, A.Col2
FROM A
LEFT JOIN B ON A.Key = B.Key
``` | How to join two tables | [
"",
"sql",
"oracle",
"join",
""
] |
```
CREATE TABLE IF NOT EXISTS `accesscards` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`department` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`entrydates` datetime NOT NULL, PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
INSERT INTO `accesscards` (`id`, `departmen... | ```
SELECT a1.*
FROM accesscards a1
JOIN (SELECT name, MIN(entrydates) mindate
FROM accesscards
WHERE name != ''
GROUP BY name, date(entrydates)) a2
ON a1.name = a2.name AND a1.entrydates = a2.mindate
```
[DEMO](http://www.sqlfiddle.com/#!2/66c3f/3) | If you are using mysql : [GROUP\_CONCAT](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) and [SUBSTRING\_INDEX](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index)
```
SELECT
DATE(entrydates) AS grouped_date,
GROUP_CONCAT(id ORDER BY entryda... | Get records for each person's each day's min datetime | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
**EDIT VERSION**
**EMPLOYEE TABLE**
```
|ID | employee_id | Name |
| 1 | 123 | John Richard |
| 2 | 554 | Daniel Domingo |
```
**educational background**
```
|ID | employee_id | School/institute | date graduated |
| 1 | 123 | highschool | 2007 ... | Try this:
```
SELECT *
FROM (SELECT * FROM tableA ORDER BY employee_id, date_graduated DESC) A
GROUP BY employee_id
```
**OR**
```
SELECT a.*
FROM tableA a
INNER JOIN (SELECT employee_id, MAX(date_graduated) maxDate
FROM tableA GROUP BY employee_id
) b ON a.employee_id = b.employee_id AND a... | ```
SELECT employee_id ,MAX([date graduated]) FROM Table GROUP BY [employee_id]
```
The result is
```
employee_id | date graduated
----------------------------
123 | 2011
554 | 2013
``` | how to select most recent date in mysql | [
"",
"mysql",
"sql",
"select",
"group-by",
"sql-order-by",
""
] |
In my situation, I need to deal with invalid date values like: '04070$'. I need to insert something even if I receive erroneous inputs like: '04070$'.
When I do:
```
select str_to_date('04070$','%m%d%Y') from dual;
```
The result is:
```
2000-04-07
```
But for insert statement, I get an error:
```
INSERT INTO `ta... | It happens because MySQL is running on [Strict Mode](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict).
On a `SELECT` statement, `STR_TO_DATE()` will return a year, but since it wasn't matched 100%, it'll also issue a warning:
```
mysql> SELECT str_to_date('040710$','%m%d%y');
+------------------... | Change the year format to uppercase like.
```
str_to_date('01-01-2000','%d-%m-%Y')
``` | Truncated incorrect date value | [
"",
"mysql",
"sql",
"date",
""
] |
While working with following query on mysql, Its getting locked,
```
SELECT event_list.*
FROM event_list
INNER JOIN members
ON members.profilenam=event_list.even_loc
WHERE (even_own IN (SELECT frd_id
FROM network
WHERE mem_id='911'
GROUP BY... | Try this:
```
SELECT el.*
FROM event_list el
INNER JOIN members m ON m.profilenam = el.even_loc
WHERE el.even_active = 'y' AND
(el.even_own = 911 OR EXISTS (SELECT 1 FROM network n WHERE n.mem_id=911 AND n.frd_id = el.even_own))
GROUP BY el.even_id
ORDER BY el.even_stat ASC
``` | You don't need the `GROUP BY` on the inner query, that will be making the database engine do a lot of unneeded work. | How to optimize this complected query? | [
"",
"mysql",
"sql",
"performance",
"select",
"query-optimization",
""
] |
Say I have the following:
```
PART SUBPART QUANTITY
-------- -------- -----------
01 02 2
01 03 3
01 04 4
01 06 3
02 05 7
02 06 6
03 07 6
04... | "For each part I need the subpart that has the maximum quantity". How about this?
```
select t.*
from mytable t join
(select part, max(quantity) as maxq
from t
group by part
) m
on m.part = t.part and m.maxq = t.quantity;
``` | I assume DB2 for AS400 doesn't support MAX OVER, i.e. Windowed Aggregate Functions?
Then it would be easy, otherwise you need a correlated subquery:
```
with T (PART, SUBPART1, SUBPART2, SUBPART3, SQ) AS
(SELECT PART, SUBPART1, SUBPART2, SUBPART3, SUM(QUANTITY)
FROM MYTABLE
GROUP BY PART, SUB... | Select a composite key, where max(column_value) | [
"",
"sql",
"db2",
"ibm-midrange",
"aggregation",
""
] |
I wanted to take average of two columns and display in a new column something like this:
```
+-+--+--+--+--------+--------+
|A|B |C |D |AVG(B/C)|AVG(C/B)|
+-+--+--+--+--------+--------+
|S|23|34|56| | |
+-+--+--+--+--------+--------+
|T|45|6 |79| | |
+-+--+--+--+--------+--------+
```
So, ... | You should give it a try:
```
SELECT A, AVG((B+C)/2) as bc, AVG((C+B)/2) as cb
FROM tableTest
WHERE A = 'S'
GROUP BY A
``` | A`VG(col1/col2)` is not the same as `AVG((col1+col2/2)`.
How about using `GROUP BY`?
> SELECT city, "average money spend:", AVG( sales-profit/
> number-of-customer) FROM Sales GROUP BY City
Then better use
> SUM(sales-profit)/SUM(number-of-customers)
or use
> AVG(sales-profit)/AVG(number-of-customers)
(but this ... | Average of two columns in SQL | [
"",
"sql",
"database",
"postgresql",
"average",
""
] |
i have a mysql customers table:
```
customer_id | customer_name | creation_date
1 | john | 2013-09-12 18:34:00
2 | banjo | 2013-01-11 14:34:00
```
what i would to achieve is to know the closest DAY in the current ot next month that match the creation\_date field.
I.E if the curre... | The following seems to work but not tested for edge cases:
```
SELECT
CURRENT_DATE AS cutoff_date,
date_column AS creation_date,
CASE
WHEN STR_TO_DATE(CONCAT_WS('-', YEAR(CURRENT_DATE), MONTH(CURRENT_DATE), DAY(date_column)), '%Y-%c-%e') >= CURRENT_DATE
THEN STR_TO_DATE(CONCAT_WS('-', Y... | First calculate the wanted date, than use min/max to get the closest one. Maybe something like that:
```
-- If your stored date is always in year 2013
select CASE WHEN DATE_ADD(DATE_ADD(creation_date, INTERVAL 1 YEAR), INTERVAL 1 MONTH) < SYSDATE
THEN DATE_ADD(creation_date, INTERVAL 1 YEAR)
EL... | mysql next date by day of one field | [
"",
"mysql",
"sql",
"date",
"datetime",
""
] |
I dont know much about SQL, and I've got a problem using it.
I have two tables that connected to each other 1-1
Tbl1 (int\_id1, str\_desc1,....) and
Tbl2 (int\_id2, str\_desc2,....)
And these two are connected to each other
int\_id1 ---- int\_id2
First I want to know that is my design true?
And how can I... | It means you are trying to insert a value in a Foreign Key Column which does not exist in the Primary Key Column which it referencing to.
Any value you add in a Foreign Key Column, It must Exist in the Primary Key Column to which it referencing to, after all that is the whole Idea of adding Foreign Key Constraints. so... | > First I want to know that is my design true?
When you have tables in a one to one relationship, the first question should be: why not just use one table? There may not be a need to separate the data. | How can I insert into a table that is connected to another table with a 1-1 relationship | [
"",
"sql",
"sql-server",
""
] |
When we create a database with a column as date , it can have the type date . But in the startup , I am interning they use int(11) as type to store a date as yyyymmdd eg(20140121) . So is there any advantage of using it or is it just a matter of choice.. | I would recommend using the DATETIME data type within SQL Server. Not necessarily for performance reasons, but to leverage the RDBMS-specific functionality. For instance, you would have to re-invent a lot of logic just to do basic date math (think DATEDIFF(), DATEADD(), DATEPART() and many other functions. They are obv... | Integer encoded dates (e.g. 20140121) are common in warehouse databases.
Whether it's a good idea depends somewhat upon which RBDMS you are using. In some instances they use less space than an equivalent datetime datatype, and they are readable in a raw data form.
For example, it used to be the recommended approach i... | The Date in a Database should be Date type or int(11)? | [
"",
"sql",
""
] |
It's my table t1; It has one million rows.
```
CREATE TABLE `t1` (
`a` varchar(10) NOT NULL,
`b` varchar(10) DEFAULT NULL,
`c` varchar(10) DEFAULT NULL,
`d` varchar(10) DEFAULT NULL,
`e` varchar(10) DEFAULT NULL,
`f` varchar(10) DEFAULT NULL,
`g` varchar(10) DEFAULT NULL,
`h` varchar(10) DEFAULT NULL,
... | Try `select * from t1 where a='10000000';`.
You're probably forcing MySQL to convert all of those strings to integers - because integers have a higher type precedence than `varchar` - in which case an index on the strings is useless
---
Actually, apparently, I was slightly wrong. By my reading of the [conversions](h... | Data is stored in blocks in almost all databases. Reading a block is an elementary Unit of IO.
Indexes helps the system in zeroing in on the datablock which holds the data that we are trying to read and would avoid reading all the datablocks. In a very small table which has single or very few data blocks the usage of i... | Why primary key has no good effect on select? | [
"",
"mysql",
"sql",
"select",
""
] |
I have a table with with a latitude, longitude and coordinates column. There are over 500,000 rows. The coordinates field is currently empty on every row. What I need to do is convert the latitude and longitude into a Geospatial POINT() and put it in the coordinates column. Is this possible?
I know that `POINT`s can b... | A GeomFromText needs a string, you've got to lot of concatenate
```
INSERT INTO myTable (coordinates)
SELECT GeomFromText(CONCAT('POINT(',ot.latitude, ' ', ot.longitude,')'))
FROM otherTable ot;
```
If it's an update to an existing table with `latitude` and `longitude` columns into a new column `coordinates`... | This is a older question but I have remarked that all answers are wrong (at least in 2019) latitude and longitude must be opposite as the answers
instead: `POINT(latitude,longitude)`
**Must be:** `POINT(longitude,latitude)`
In Mysql 5.6 and later can use :
```
Update myTable
Set coordinates = POINT(longitude, latit... | Convert latitude/longitude fields into Geospatial Points | [
"",
"mysql",
"sql",
"geospatial",
""
] |
I need some help with the SUM feature. I am trying to SUM the bill amounts for the same account into one grand total, but the results I am getting show my SUM column just multiples my first column by 3.
Here is what I want as results for my mock data:
```
AccountNumber Bill BillDate
1 100.00... | Thank you for your responses. Turns out my problem was a database issue with duplicate entries, not with my logic. A quick table sync fixed that and the SUM feature worked as expected. This is all still useful knowledge for the SUM feature and is worth reading if you are having trouble using it. | If you don't want to group your result, use a window function.
You didn't state your DBMS, but this is ANSI SQL:
```
SELECT AccountNumber,
Bill,
BillDate,
SUM(Bill) over (partition by accountNumber) as account_total
FROM Table1
order by AccountNumber, BillDate;
```
Here is an SQLFiddle: <http... | SQL Sum Multiple rows into one | [
"",
"sql",
"function",
"group-by",
"sum",
""
] |
I have the following table for evaluating students:
```
StudentID | EvaluationStatusID| Date
1011010 | 1 |2013-11-07 20:31:51.000
1011020 | 1 |2013-11-08 13:23:51.000
1011010 | 2 |2013-11-08 20:31:51.000
1011020 | 3 |2013-11-09 20:31:51.000
```
T... | The simplest is using ranking functions like `ROW_NUMBER`.
```
WITH CTE AS
(
SELECT StudentID, EvaluationStatusID, Date,
RN = ROW_NUMBER() OVER (PARTITION BY StudentID
ORDER BY Date DESC)
FROM dbo.Student
)
SELECT StudentID, EvaluationStatusID, Date
FROM CTE WHERE ... | ```
SELECT StudentID +' ' +EvaluationStatusID
FROM tblTable T
WHERE T.Date = (SELECT MAX(TT.Date)
FROM tblTable TT
WHERE TT.StudentID = T.StudentID
)
``` | Retrieve last entry for each | [
"",
"sql",
"sql-server",
""
] |
I have table A with below records:
Table A
```
+----+-----+
|Tuid|Etuid|
+----+-----+
|d1 |E1 |
+----+-----+
|d2 |E1 |
+----+-----+
|d3 |E2 |
+----+-----+
|d4 |E3 |
+----+-----+
|d5 |E4 |
+----+-----+
```
Table B
```
+----+---+
|Tuid|FID|
+----+---+
|d1 |1 |
+----+---+
|d2 |2 |
+----+---+
|d3 |1... | Try this code (not tested)
```
select a.ETuid
from tablea a
join tableb b on (a.ETuid= b.ETuid)
where b.fid in (1,2)
group by a.ETuid
having count(distinct b.fid) = 2
``` | This may not be an elegant solution, but the logic is pretty straight forward:
```
SELECT a1.Etuid
FROM TableA a1
INNER JOIN TableB b1 ON (a1.Tuid=b1.Tuid)
WHERE b1.FID=1
INTERSECT
SELECT a2.Etuid
FROM TableA a2
INNER JOIN TableB b2 ON (a2.Tuid=b2.Tuid)
WHERE b2.FID=2;
```
Outputs
```
ETUID
E1
E2
E3
```
... | Correct Oracle Query | [
"",
"sql",
"database",
"oracle",
""
] |
I have two tables. Table A contains daily information on transactions on corporate bonds from 2004 to 2012, and table B contains bond rating information on specific dates. I need to join the two tables, so that for each transaction i table A, the most recent rating for that specific bond is appended.
```
Table A: dail... | I managed to bring down the runtime to 5 minutes by indexing on the `bond` column.
```
proc sql;
create index bond
on work.daily_transactions(bond);
quit;
proc sql;
create index bond
on work.bond_ratings(bond);
quit;
``` | For a more SAS based approach (instead of SQL), you can use a SAS format for Table B and probably speed it up more. A [format in SAS](http://support.sas.com/documentation/cdl/en/proc/61895/HTML/default/viewer.htm#a002473491.htm) is just a lookup table mapping anything between START and END to a LABEL. For example, load... | How to join with most recent record? | [
"",
"sql",
"performance",
"sas",
""
] |
I have stored procedure which is building dynamic SQL statement depending on its input parameters and then executed it.
One of the queries is causing time outs, so I have decided to check it. The first time (and only the first time) the issue statement is executed it is slow (30 secs - 45 secs) and every next execute ... | From your reply to my comment, it would appear that the first time this query runs it is performing a lot of physical reads or read-ahead reads, meaning that a lot of IO is required to get the right pages into the buffer pool to satisfy this query.
Once pages are read into the buffer pool (memory) they generally stay ... | Its very simple the reason 1st and very 1st time it takes longer and then all later executions are done fairly quickly. the reason behind this mystery is "CACHED EXECUTION PLANS".
> While working with Stored Procedures, Sql server takes the following
> steps.
>
> 1) Parse Syntax of command.
> 2) Translate to Query... | Dynamic SQL - long execution time - first time only | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I want to select the number of users that has marked some content as favorite and also return if the current user has "voted" or not. My table looks like this
```
CREATE TABLE IF NOT EXISTS `favorites` (
`user` int(11) NOT NULL DEFAULT '0',
`content` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`user`,`content`)
) ENG... | This is because you mixed aggregated and non-aggregated expressions in a single `SELECT`. Aggregated expressions work on many rows; non-aggregated expressions work on a single row. An aggregated (i.e. `COUNT(*)`) and a non-aggregated (i.e. `CASE`) expressions should appear in the same `SELECT` when you have a `GROUP BY... | Try this with `SUM()` and without `CASE`
```
SELECT
COUNT(*),
SUM(USER = '22') AS has_voted
FROM
favorites
WHERE content = '26977'
```
[**See Fiddle Demo**](http://sqlfiddle.com/#!2/c249b/4) | SELECT CASE, COUNT(*) | [
"",
"mysql",
"sql",
"select",
"max",
"case",
""
] |
I have data like this:
```
Product Group Product Level Quatity Sold Trend
==============================================================
Group 1 L1 10 up
Group 1 L2 20 up
Group 1 L3 30 down
G... | You could get the desired result by implementing the PIVOT function, but I would first UNPIVOT your multiple columns of `Quantity Sold` and `Trend`. The unpivot process will convert them from multiple columns into multiple rows of data.
Since you are using SQL Server 2008+, you can use `CROSS APPLY` with `VALUES` to u... | You can potentially do this using correlated subqueries:
```
select productGroup as [Product Group]
, (select sum(quantitySold) from myTable where productGroup = a.productGroup and productLevel = 'L1') as L1
, (select max(trend) from myTable where productGroup = a.productGroup and productLevel = 'L1') as L1Tre... | PIVOT on Multiple Columns | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008-r2",
"pivot",
""
] |
here
```
SELECT
COUNT(*)
FROM
tbl_department
RIGHT JOIN tbl_video
ON tbl_video.department_id = tbl_department.department_id
LEFT JOIN tbl_language
ON tbl_language.language_id = tbl_video.video_language
WHERE tbl_video.department_id LIKE '%1%'
```
i already tried
```
SELECT
COUNT(*)
FROM
... | When you use (\*) it implies all columns , "AS" can be used for one column , so column from a table tbl\_department with an one column . | Use as in select
i.e
```
SELECT
COUNT(*) AS numbers
.....
```
Dont use AS somewhere..Use it in select | how do i use "as" in this SQL statement? | [
"",
"mysql",
"sql",
"sql-server",
"phpmyadmin",
""
] |
Suppose I want to return the number '1' if EXISTS (customers.salary>'1000')
I tried:
```
SELECT 1
FROM customers
WHERE EXISTS (customers.salary>'1000')
```
also this could work:
```
SELECT COUNT(salary)
FROM (SELECT DISTINCT(salary) FROM (SELECT salary FROM costomers WHERE salary>'1000'));
```
but what if I would ... | ```
SELECT
CASE WHEN (customers.salary>1000) THEN 1 ELSE 0 END AS overThousand
FROM customers
```
Will bring back a 1 for each row where salary is over 1000. So if you also took your customer name, your results woul be "bob, 1" (Salary over 1000), "Dave, 0" (Salary under 1000).
If you literally just want a '1'... | You can return any number of your choice through your first query, or even an expression.
```
SELECT 10
FROM customers
WHERE EXISTS (customers.salary>'1000')
```
You can check the syntax of [SELECT](http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#i2065706) statement for more on this, and th... | How can you return an integer if a certain condition is met in SQL? | [
"",
"sql",
""
] |
I've been looking for a bit, but haven't found a good answer.
I've found that I could generate the code in a VBA procedure and run it from there, however, i'm working on someone else's design and don't want to change it up too much.
In part of that pass-through query we have something like this:
```
WHERE (((ID='380'... | After looking around a lot and researching a bit it seemed that only a stored procedure on the server (Which I cannot do) or creating a string and passing that string to the pass-through query are my options.
I'm going to pursue the string option since it seems like the best option with my constraints here. if anyone c... | You can set the combobox to put the selected value in a cell, and then link the query to the value of that cell via a parameter.
Cheers - | Access Dynamic Pass-through Query | [
"",
"sql",
"ms-access",
"vba",
"pass-through",
""
] |
I have table test0. This table referenced by tables:
```
test1
test2
test3
....
test150
```
Does it possible write simple short query to delete 1 row in table test0 and if they exist - in all tables test1 ... test150 ? | Try this function to get delete script for all of the child rows of the given parent row:
```
Create or replace
FUNCTION FN_GET_DELETE_SCRIPT
( Parent_ID IN VARCHAR2, Parent_Table_Name in varchar2
) RETURN varchar2
AS
sql_statement varchar2(200);
script varchar2(4000);
n pls_integer;
Tot Pls_Integer := 0;
Cc_Id Va... | * Try like this
```
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
(product_id numeric(10) not null,
supplier_id numeric(10) not nul... | How to delete all referential tables in Oracle? | [
"",
"sql",
"oracle",
"foreign-keys",
""
] |
I have an SQL table contains data for the sale of some items. In fact, it has the logs of the sale of items.
For example, there is a sale that contains 2 items: Keyboard (`id:1`) and mouse(`id:2`). Buyers can make bids to each item and multiple times, like ebay. So let's assume there are 2 buyers(`ids are 97 and 98`) ... | ```
SELECT o.`bid_id`,o.`buyer_id`,o.`item_id`,o.`amount`,o.`time` FROM `offers` o
JOIN
(SELECT MIN(`bid_id`) AS `bid_id`,`buyer_id`,`item_id`,`amount`,`time` FROM `offers` GROUP BY `buyer_id`,`item_id`)x
ON x.bid_id=o.bid_id AND x.buyer_id=o.buyer_id
``` | Here's another take, using [Quassnoi's ranking trick here](https://stackoverflow.com/questions/532878/how-to-perform-grouped-ranking-in-mysql/532941#532941)
For the first bids:
```
SELECT x.bid_id, x.buyer_id, x.item_id, x.amount, x.time
FROM
(
SELECT o.bid_id, o.buyer_id, o.item_id, o.amount, o.time,
@combo... | MySQL: SELECT First or Last Rows When Grouping By Multiple Columns | [
"",
"mysql",
"sql",
"select",
"group-by",
"distinct",
""
] |
my code gives TOTAL HOURS in hours, but i am trying to output something like
```
TotalHours
8:36
```
where 8 represents hour part and 36 represents minutes part mean totalHours a person has worked in a single day at office.
```
with times as (
SELECT t1.EmplID
, t3.EmplName
, min(t1.RecTime) AS... | Small change like this can be done
```
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, CASE WHEN minpart=0
THEN CAST(hourpart as nvarchar(200))+':00'
ELSE CAST((hourpart-1) as nvarchar(200))+':'+ CAST(minpart as nvarchar(200))END as 'total ti... | Very simply:
```
CONVERT(TIME,Date2 - Date1)
```
For example:
```
Declare @Date2 DATETIME = '2016-01-01 10:01:10.022'
Declare @Date1 DATETIME = '2016-01-01 10:00:00.000'
Select CONVERT(TIME,@Date2 - @Date1) as ElapsedTime
```
Yelds:
```
ElapsedTime
----------------
00:01:10.0233333
(1 row(s) affected)
``` | DateDiff to output hours and minutes | [
"",
"sql",
"sql-server",
""
] |
I am using SQL Server 2005.
I'm having some issues when executing this query.
My code is
```
ALTER PROCEDURE [dbo].[Get]
@ApplicantID int
AS
BEGIN
SELECT
isnull(M_EvalApplicationStatuses.EvalApplicationStatus,'') EvalApplicationStatus,
isn... | As per your comment in sarathkumar's answer the problem is Ambiguous column name 'ApplicantID'. Try the below for that problem. I have updated the `where clause` from your comment.
```
left outer join [APP_DocumentTracking] on [APP_DocumentTracking].ApplicantID=APP_Applications.ApplicantID
WHERE [APP_DocumentTracking... | Just join as a subquery with first and second one .Please update the structure in SqlFiddle or here Itself.Then it will be easy to give u the answer...
Here is the code
```
ALTER PROCEDURE [dbo].[Get]
@ApplicantID int
AS
BEGIN
SELECT
isnull(M_EvalApplicat... | SQL Query join issues | [
"",
"sql",
"sql-server",
"join",
""
] |
I have table like this:
```
+--------+--------+--------+
| color | fruit | amount |
+--------+--------+--------+
| red | cherry | 124 |
| red | plum | 23 |
| green | gauva | 119 |
| green | pear | 14 |
| orange | orange | 23 |
+--------+--------+--------+
```
I want it to add rank lik... | ```
select
color, fruit, amount,
case when (if(@prev_color != color, @rank:=1, @rank:=@rank + 1)) is null then null
when (@prev_color := color) is null then null
else @rank end as rank
from your_table
, (select @rank:=0, @prev_color := null) v
order by color, amount desc
``` | If the ranks are given based on the high `amount` of `color` availability, then you can also find number of rows less or more than with the `amount` value. That number of rows would be the `rank` for the concerned `color`.
```
select
( select count( color ) from fruits_table
where color = f.color and amount >= f.... | Rank sql columns | [
"",
"mysql",
"sql",
""
] |
Say I have a table called `PHRASES` containing some text strings
```
+--+---------------+
|ID|PHRASE |
+--+---------------+
|0 |"HELLO BYE YES"|
+--+---------------+
|1 |"NO WHY NOT" |
+--+---------------+
|2 |"NO YES" |
+--+---------------+
```
And I want to add the number of times each of the follow... | Well this seems to work
```
MERGE INTO KEYWORDS masterList
USING (
SELECT COUNT(*) AS OCCURRENCE,KEYWORDS.KEYWORD AS KEYWORD FROM
KEYWORDS AS keywordList
CROSS JOIN PHRASES AS phraseList
WHERE (dbo.RegExIsMatch('.*' + keywordList.KEYWORD + '.*',phraseList.PHRASE,1) = 1)
GROUP BY KEYWORD
) frequenc... | Your query has three different tables, but the question only two. Is this what you mean?
```
UPDATE Keywords
SET OCCURRENCE = (SELECT SUM(CASE WHEN dbo.RegExIsMatch('.*' + KEYWORDS.KEYWORD + '.*',PHRASES.PHRASE,1) = 1
THEN 1 ELSE 0
END)
... | How do I count the number of times each keyword from a table appears in a table of phrases? | [
"",
"sql",
"sql-server-2008",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.